tags:

views:

2982

answers:

4

Sql server complaining about this IF NOT EXISTS statement, saying that there is 'incorrect syntax near the keyword 'OR'.

My query:

IF NOT EXISTS ( 
                (SELECT * FROM Users where userID = 1)
                OR
                (SELECT * FROM sales WHERE saleID = 1)
              )
BEGIN
            // blah blah blah

END
+2  A: 

you want IF NOT EXISTS ( SELECT... ) AND NOT EXISTS ( SELECT .... )

Andy Lester
why can't I do both in a single statement though? it makes no sense!
actually that should be ... OR NOT EXISTS ...
@Blankman: EXISTS takes a single select as its parameter
Steven A. Lowe
@Blankman: No, it should be AND NOT EXISTS because you are changing from IF NOT ( A OR B ) to IF (NOT A) AND (NOT B). See DeMorgan's laws: http://en.wikipedia.org/wiki/De_Morgan%27s_laws
Andy Lester
+8  A: 

try it this way instead

IF 
    NOT EXISTS (SELECT 1 FROM Users where userID = 1)  
AND 
    NOT EXISTS (SELECT 1 FROM sales WHERE saleID = 1)
BEGIN 
       -- blah blah blah
END

or, if you insist on a disjunction:

IF NOT (
    EXISTS (SELECT 1 FROM Users where userID = 1)  
    OR 
    EXISTS (SELECT 1 FROM sales WHERE saleID = 1)
)
BEGIN 
    -- blah blah blah
END

the EXISTS operator takes a single select statement and checks for any results (so you can use a constant 1 instead of * or a column name, it's more efficient)

Steven A. Lowe
ahh ok, I'm trying to bring my C# syntax to the 'table' haha
A: 

Maybe this is what you are trying to do:

IF NOT EXISTS(SELECT * FROM Users WHERE userID = 1) OR (AND) NOT EXISTS(SELECT * FROM sales WHERE saleID = 1)
dragonjujo
+1  A: 

change "or" to "union"

as long as the same set of fields is returned by both queries, this would work
Steven A. Lowe