Question

I keep looking at this and do not understand why I am not getting a result set back here are my my queries

SELECT UserID FROM @SelectedID 
SELECT UserID FROM @SelectedIdValue
SELECT UserID FROM @SelectedID WHERE NOT EXISTS (SELECT UserID FROM @SelectedIdValue

And here is the result set returned

enter image description here

As you can see 194 does not exist in the second result set so why am I not getting 194 returned? Am I using NOT EXISTS wrong here?

Était-ce utile?

La solution

You need a correlated subquery:

SELECT UserID
FROM @SelectedID si
WHERE NOT EXISTS (SELECT 1
                  FROM @SelectedIdValue siv
                  WHERE si.UserId = siv.UserId
                 );

Your version of the query simply returned false for all rows. The subquery returns a value, so something exists.

EDIT:

You can phrase this as a left outer join if you want:

SELECT si.UserID
FROM @SelectedID si LEFT OUTER JOIN
     @SelectedIdValue siv
     ON si.UserId = siv.UserId
WHERE siv.UserId IS NULL;

Autres conseils

The exists subquery only checks whether user ids exist, not what their value is. If you replace "not exists" with "UserID not in" your query will return the expected result. Note though that "in" doesn't work as expected when there are null values in the column, verify if that's possible before using "in".

SELECT userid 
FROM   @SelectedID 
WHERE  userid NOT IN (SELECT userid 
                      FROM   @SelectedIdValue) 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top