Sql server抱怨这个IF NOT EXISTS语句

时间:2008-11-14 16:14:40

标签: sql-server

Sql server抱怨这个IF NOT EXISTS语句,说关键字'OR'附近有'错误的语法。

我的查询:

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

END

4 个答案:

答案 0 :(得分:8)

尝试这种方式而不是

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

或者,如果你坚持分离:

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

EXISTS运算符采用单个select语句并检查任何结果(因此您可以使用常量1而不是*或列名,它更有效)

答案 1 :(得分:3)

你想要IF NOT EXISTS(SELECT ...)和NOT EXISTS(SELECT ....)

答案 2 :(得分:1)

将“或”改为“工会”

答案 3 :(得分:0)

也许这就是你想要做的事情:

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