在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
。
答案 0 :(得分:2)
WHERE Name = @name
AND (@someINT IS NULL OR SomeInt = @someINT)
答案 1 :(得分:2)
另一个选择是
WHERE Name = @name
and someInt = Isnull(@someINT , someInt)