相当于SQL中的VB AndAlso?
SQL中是否有相当于VB的AndAlso
/OrElse
和C#的&&
/||
(SQL服务器 2005)。我正在运行类似于以下内容的选择查询:
SELECT a,b,c,d
FROM table1
WHERE
(@a IS NULL OR a = @a)
AND (@b IS NULL OR b = @b)
AND (@c IS NULL OR c = @c)
AND (@d IS NULL OR d = @d)
例如,如果作为 NULL 传入的“@a”参数,则评估 WHERE 子句的第二部分 (a = @a) 是没有意义的。有没有办法通过使用特殊语法或重写查询来避免这种情况?
谢谢, 詹姆斯.
Is there an equivalent to VB's AndAlso
/OrElse
and C#'s &&
/||
in SQL (SQL Server 2005). I am running a select query similar to the following:
SELECT a,b,c,d
FROM table1
WHERE
(@a IS NULL OR a = @a)
AND (@b IS NULL OR b = @b)
AND (@c IS NULL OR c = @c)
AND (@d IS NULL OR d = @d)
For example, if the "@a" parameter passed in as NULL there is no point in evaluating the 2nd part of the WHERE clause (a = @a). Is there a way to avoid this either by using special syntax or rewriting the query?
Thanks,
James.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
保证评估顺序的唯一方法是使用 CASE
根据我的经验,这通常比让数据库引擎对其进行排序要慢。
TerrorAustralis 的答案通常是不可空列的最佳选择
The only way to guarantee the order of evaluation is to use CASE
In my experience this is usually slower then just letting the DB engine sort it out.
TerrorAustralis's answer is usually the best option for non-nullable columns
试试这个:
这个函数查看@a。如果不为 null,则等于表达式
如果为 null,则等于表达式
(因为这始终为 true,所以它替换 @b is null 语句)
Try this:
This function looks at @a. If it is not null it equates the expression
If it is null it equates the expression
(Since this is always true, it replaces the @b is null statement)
查询引擎将为您处理这个问题。正如您所写的那样,您的查询没有问题。如果可以的话,所有运营商都会“短路”。
The query engine will take care of this for you. Your query, as written, is fine. All operators will "short circuit" if they can.
另一种方法是:
条件后面的另一个 if 将执行“AndAlso”逻辑。
我想强调的是,这只是一种简短的写法:
Another way is to do:
Another if after the condition will do an "AndAlso" logic.
I want to emphesise that this is just a short way to write:
举个例子:
Orders.OrderId
is varchar(25)dbo.JobIsPending(OrderId)
UDF with int 参数dbo 中转换失败,不会造成短路.JobIsPending(OrderId) 当
Orders.OrderId NOT LIKE '%[0-9]%'
在 SQL Server 2008 R2 上测试
Take this example:
Orders.OrderId
is varchar(25)dbo.JobIsPending(OrderId)
UDF with int parameterNo short circuit is made as the conversion fails in
dbo.JobIsPending(OrderId) when
Orders.OrderId NOT LIKE '%[0-9]%'
tested on SQL Server 2008 R2