SQL Server字符串拼接的结果为NULL的问题

问题

某个存储过程的参数有一个输出参数:@msg nvarchar(1024) output ,拼接的字符串会赋值给@msg,然后C#代码获取@msg后显示到界面上。

通过测试后发现字符串和变量拼接竟然变成了空字符串:

1
2
3
4
5
6
7
declare @msg nvarchar(512)
declare @name varchar(50)
set @name='gan'
declare @time datetime
-- CONVERT(varchar,@time,20)是将时间格式化输出
set @msg= 'test: ' + CONVERT(varchar,@time,20) + CAST(@name as varchar)
select '1' + @msg + '2'

image-20210528125127257

解决

本以为使用convert和cast将类型转换为varchar字符类型就没有问题了。

检查发现,是由于@time为NULL导致的(变量声明之后的默认值为NULL)。

解决办法就是使用 isnull 将为NULL的变量转换为空字符串:

1
2
3
4
5
6
7
declare @msg nvarchar(512)
declare @name varchar(50)
set @name='gan'
declare @time datetime
select @time
set @msg= 'test: ' + CONVERT(varchar,ISNULL(@time, ''),20) + CAST(ISNULL(@name, '') as varchar)
select '** ' + @msg + ' **'

image-20210528125103252

SQL Server字符串拼接的结果为NULL的问题

https://ganzhixiong.com/p/93f760c5/

Author

干志雄

Posted on

2019-05-12

Updated on

2019-05-12

Licensed under

Comments