I am trying to delete some data from a table variable using a SELECT query. The following code works perfectly:
DECLARE @sgID int
SET @sgID = 1234
DELETE FROM
@tbl_users
WHERE
(userID NOT IN (
SELECT
userID
FROM
[SGTable]
WHERE
(sgID = @sgID)
))
I’m trying to speed up this query, and read that the following approach may be better. However, when I use the following code – ALL records are deleted from the table variable.
DELETE
tmp
FROM
@tbl_Users tmp INNER JOIN
[SGTable] sgu ON sgu.userID = tmp.userID
WHERE
(sgu.sgID <> @sgID)
I (obviously incorrectly) assumed that these two queries did the same thing (delete all userIDs in the table variable where the userID is not found in the sub-query). Can anyone please offer some advice on making the second query work, as it is obviously easier to read and maintain?
Is it possible that a userID can be associated with more than one sgID in SGTable?
If so, then you’re deleting users in your sgID (@sgID) because they are also associated with another sgID.
You might prefer: