sql 短路 OR 或条件存在于 where 子句中 [英] Sql short circuit OR or conditional exists in where clause

查看:81
本文介绍了sql 短路 OR 或条件存在于 where 子句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试强制 sql server 对某些字段进行短路或比较.在 Or 的左侧,我有一个简单的变量比较,在右侧,我有一个非常重"的子查询.

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)

如果第一条语句为假,有没有办法只执行or语句的右侧.

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

我尝试过 case 和 if else 语句,但找不到任何有效的语法.

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

我使用的是 MS SQL 服务器

I'm using a MS SQL server

推荐答案

你不能在一条 SQL 语句中做你想做的事.你可以在存储过程中做这样的事情

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

如果你有很多输入,你应该考虑动态 SQL

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

这篇关于sql 短路 OR 或条件存在于 where 子句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆