如何在SQL Server中的动态查询中处理空值?

时间:2015-05-22 12:31:33

标签: sql-server sql-server-2008

我想在SQL Server过程中管理动态空值。我准备了以下演示,假设@userid是存储过程的输入参数

declare @userID  int =null
declare @suerid varchar(100)=@userid
select cast(@userID as nvarchar(100))

declare @sql nvarchar(2000)
set @sql ='select * from users where userid=isnull('+@suerid+',@suerid)'
print @sql 
EXECUTE sp_executesql @sql

当我在@userid中传递有效整数值时,它会给出欲望输出,但是当我尝试传递@userid=NULL时,它没有给出任何输出。我想要 通过@userid=NULL

3 个答案:

答案 0 :(得分:2)

首先是这一行:

SET @sql = 'SELECT * FROM users WHERE userid = ISNULL(' + @suerid + ', @suerid)'

您将遇到语法错误,因为您@suerid内未声明@sql,所以您应该这样:

SET @sql = 'SELECT * FROM users WHERE userid = ' + ISNULL(@suerid, 0)

如果你想在输入参数为null时返回一行NULL,我建议你使用这个语法:

SET @sql = 'SELECT u.* ' +
           'FROM users u ' +
             'RIGHT JOIN ' +
                '(SELECT ' + ISNULL(@suerid, 'NULL') + ' AS ID) N ' +
             'ON u.userid = N.ID ' +
           'WHERE ISNULL(u.userid, -1) = ' + ISNULL(@suerid, '-1')

答案 1 :(得分:1)

也许这就是你想要的:

DECLARE @userID int
DECLARE @sql nvarchar(2000)
SET @sql = N'SELECT * FROM users WHERE ' + CASE WHEN @userID IS NULL THEN 'userid IS NULL' ELSE 'userid = @userId' END
EXEC sp_executesql @sql, '@userId int', @userID

修改

如果您输入NULL,并希望取消所有用户:

DECLARE @userID int
DECLARE @sql nvarchar(2000)
SET @sql = N'SELECT * FROM users WHERE (userid = @userId or @userId is null)'
EXEC sp_executesql @sql, '@userId int', @userID

修改

甚至更简单:

DECLARE @userID int
SELECT * FROM users WHERE (userid = @userId or @userId is null)

答案 2 :(得分:0)

你真的需要一个动态的SQL查询吗?动态sql是risky并且执行起来很慢,我建议尽可能避免它,即使它意味着编写更多代码。
如果必须使用动态sql,请尝试:

set @sql ='select * 
           from users 
           where userid = isnull('+ COALESCE(@suerid, 'null') +',@suerid)'

将空值连接到字符串时,整个字符串变为空。