5

SQL (SQL Server 2005) 中是否有等效于 VB 的AndAlso/OrElse和 C# 的&&/ ||。我正在运行类似于以下内容的选择查询:

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)

例如,如果“@a”参数作为 NULL 传入,则评估 WHERE 子句的第二部分 (a = @a) 没有意义。有没有办法通过使用特殊语法或重写查询来避免这种情况?

谢谢,詹姆斯。

4

5 回答 5

6

The only way to guarantee the order of evaluation is to use CASE

WHERE
   CASE
      WHEN @a IS NULL THEN 1
      WHEN a = @a THEN 1
      ELSE 0
   END = 1
   AND /*repeat*/

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

于 2010-07-18T12:44:49.207 回答
3

Try this:

AND a = ISNULL(@a,a)

This function looks at @a. If it is not null it equates the expression

AND a = @a

If it is null it equates the expression

AND a = a 

(Since this is always true, it replaces the @b is null statement)

于 2009-10-30T13:00:31.143 回答
2

查询引擎会为您处理这个问题。如您所写,您的查询很好。如果可以,所有运营商都会“短路”。

于 2009-10-30T11:24:07.873 回答
0

举个例子:

SELECT * FROM Orders
WHERE orderId LIKE '%[0-9]%' 
AND dbo.JobIsPending(OrderId) = 1 

Orders.OrderId是 varchar(25)

dbo.JobIsPending(OrderId)带 int 参数的 UDF

没有短路,因为转换失败dbo.JobIsPending(OrderId) when Orders.OrderId NOT LIKE '%[0-9]%'

在 SQL Server 2008 R2 上测试

于 2014-02-15T20:08:28.197 回答
0

另一种方法是:

IF (@a > 0) IF (@a = 5)
BEGIN

END

条件之后的另一个 if 将执行“AndAlso”逻辑。

我想强调这只是一种简短的写法:

IF (@a > 0) 
     IF (@a = 5)
     BEGIN

     END
于 2014-02-02T15:06:49.083 回答