为SQL中的UniqueIdentifier数据类型传递Null参数


Declare @ID uniqueidentifier =Null
select * from Emp where EmpID=@ID

上面的查询没有结果。

NULL不是一个值,而是一个状态,因此不能使用标准运算符测试等于NULL的值。

所有涉及NULL的表达都将导致NULL

DECLARE @I INT = NULL
DECLARE @A VARCHAR(20) = NULL
'Hello ' + @A + 'World' = NULL
127 * 54 - (32 / @i) = NULL

因此,当@ID为空时,您的查询select * from Emp where EmpID=@ID将不会给出结果

您需要使用特殊运算符IS NULL来测试您的参数(请参阅@Sergey评论(

select * 
from Emp 
where EmpID=@ID  /* this will catch rows when @ID is not NULL */
or (EmpID IS NULL and @ID IS NULL) /* this will catch rows when @ID is NULL */

使用像这样的ternery运算符处理它

Declare @ID nvarchar(50);
select * from Emp where EmpID=@ID is null?0:@ID;

最新更新