1

Can anyone please tell me how to write a delete statement for the following query:

      SELECT     a.UserID, b.UserEmailAddress
      FROM  tblUserProgramme AS a LEFT OUTER JOIN

      tblUser AS b ON b.UserID = a.UserID LEFT OUTER JOIN
      tblWorkGroup AS c ON c.WorkGroupID = b.WorkGroupID

      WHERE(a.ProgrammeID = 59) AND (a.UserID NOT IN

          (SELECT     UserID FROM tblUser AS a WHERE (WorkGroupID IN
             (SELECT     WorkGroupID FROM tblWorkGroup WHERE                          
             (WorkGroupName  LIKE  '%Insight%') OR (WorkGroupName LIKE '%Other%'))))) 

      AND (b.UserEmailAddress NOT IN
            (SELECT     email FROM          tmpUsers))

      ORDER BY b.UserEmailAddress

SERVER is SQL Server 2005

3
  • which database? SQL server, mysql? Commented Sep 6, 2012 at 9:36
  • have edited the question Commented Sep 6, 2012 at 9:45
  • Confusing.... could you please add bit more detail? Commented Sep 6, 2012 at 9:45

4 Answers 4

4

Query would be

Delete from 

 ( 
 SELECT     a.UserID, b.UserEmailAddress
  FROM  tblUserProgramme AS a LEFT OUTER JOIN
  tblUser AS b ON b.UserID = a.UserID LEFT OUTER JOIN
  tblWorkGroup AS c ON c.WorkGroupID = b.WorkGroupID
  WHERE(a.ProgrammeID = 59) AND (a.UserID NOT IN
(SELECT     UserID FROM tblUser AS a WHERE (WorkGroupID IN
(SELECT     WorkGroupID FROM tblWorkGroup WHERE (WorkGroupName  LIKE           
'%Insight%') OR (WorkGroupName LIKE '%Other%'))))) AND (b.UserEmailAddress NOT IN
(SELECT     email FROM          tmpUsers))
ORDER BY b.UserEmailAddress
) a
Sign up to request clarification or add additional context in comments.

Comments

3

Syntax is DB specific..
For most of tha databases this should work , if you want to delete from tblUserProgramme

DELETE A
FROM tblUserProgramme AS a 
 .....

Comments

2

In general, in SQL Server, you can delete all records which match a given SQL query as follows, provided your SELECT only returns columns from a single table:

DELETE x
FROM
(
   -- Any query which returns data from a single table, that you wish to delete
) x;

Or, using a CTE:

;WITH x as 
(
   -- Any query which returns data from a single table, that you wish to delete
)
DELETE x;

Comments

2

Thank you all for your quick answers:) There were a quite a few answers right, but had to pick the first one:)

As Joe G Joseph has mentioned, this is what i did

DELETE a
from dbo.tblUserProgramme a
LEFT OUTER JOIN tblUser b ON b.UserID = a.UserID
LEFT OUTER JOIN tblWorkGroup c ON c.WorkGroupID = b.WorkGroupID
where a.ProgrammeID = 59 AND 
a.UserID  NOT IN (SELECT UserID  FROM tblUser a WHERE a.WorkGroupID IN
(SELECT WorkGroupID FROM tblWorkGroup
WHERE WorkGroupName like '%Insight%' OR WorkGroupName like '%Other%')) 
 AND b.UserEmailAddress NOT IN(SELECT email FROM tmpUsers)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.