仅当参数不为null时才添加AND子句

时间:2017-02-06 20:04:40

标签: sql-server tsql

在SQL Server 2012中,我需要执行以下操作:

DECLARE @name VARCHAR(100) = 'Foo'
DECLARE @someINT INT = NULL

SELECT
    *
FROM
    myTable
WHERE
    Name = @name 
<IF @someINT IS NOT NULL>
    AND SomeInt = @someINT 
</IF>

仅当@someINT不为null时,才应存在AND子句。否则,我们甚至不会执行AND

2 个答案:

答案 0 :(得分:2)

WHERE Name = @name 
  AND (@someINT IS NULL OR SomeInt = @someINT)

答案 1 :(得分:2)

另一个选择是

WHERE Name = @name 
  and someInt = Isnull(@someINT , someInt)