Sql short circuit OR or conditional exists in where clause

不问归期 提交于 2021-02-11 12:29:36

问题


I'm trying to force sql server to make a short circuit OR comparison on some fields. On the left side of the Or I have a simple variable comparison and on the right side I have a pretty 'heavy' subquery.

WHERE
(@Var = 'DefaultValue' )  OR 
Exists(select * from atable)

Is there any way to only execute the right side of the or statement if the first statement is false.

I've tried case and if else statements but can't find any working syntax.

I'm using a MS SQL server


回答1:


You can't do what you want in a single SQL statement. You can do something like this however in a stored proc

If @Var = 'DefaultValue' then
BEGIN
     SELECT * FROM table 
END
ELSE
BEGIN
     SELECT * FROM table
     WHERE Exists(select * from atable)
END

If you've got a lot of inputs you should consider Dynamic SQL




回答2:


How about this?

WHERE 1 = CASE @Var
               WHEN 'DefaultValue' THEN 1
               ELSE (SELECT TOP 1 1 FROM atable)
          END


来源:https://stackoverflow.com/questions/13646009/sql-short-circuit-or-or-conditional-exists-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!