使用 COALESCE 未在 SQL 服务器中给出预期的结果
Use of COALESCE not giving the desired result in SQL Server
我有一个程序要生成一个由数组组成的类似 JSON 的字符串。
这是我正在使用的查询(以简单的脚本形式呈现):
DECLARE @_l_All_Records_Str VARCHAR(MAX)
SELECT @_l_All_Records_Str = COALESCE(@_l_All_Records_Str , ',' , '') + '["'
+ ISNULL(Time_Unit , '' ) + '","'
+ ISNULL(CAST(Periods AS VARCHAR), '' ) + '","'
+ ISNULL(Details_Present , 'N' ) + '","'
+ ISNULL(Slice_1 , '' ) + '","'
+ ISNULL(Slice_2 , '' ) + '","'
+ ISNULL(Slice_3 , '' ) + '","'
+ ISNULL(Slice_4 , '' ) + '","'
+ ISNULL(Slice_5 , '' ) + '","'
+ ISNULL(Slice_6 , '' ) + '","'
+ ISNULL(Slice_7 , '' ) + '","'
+ ISNULL(Slice_8 , '' ) + '","'
+ ISNULL(Slice_9 , '' ) + '","'
+ ISNULL(Slice_10 , '' ) + '","'
+ ISNULL(Slice_11 , '' ) + '","'
+ ISNULL(Slice_12 , '' ) + '"],'
FROM MyTable ;
SET @_l_All_Records_Str = '[' + @_l_All_Records_Str + ']' ;
print @_l_All_Records_Str ;
结果几乎正确:
[,["M","1","N","Y","Y","Y","N","Y","Y","N","N","Y","Y","Y","N"],["D","","Y","Y","N","N","N","Y","N","N","N","N","N","N","N"],]
从结果中可以看出,有额外的 ,
个字符(一个在开头,另一个在外部数组的末尾)。
有人可以建议我在这里遗漏了什么吗?
(代表问题作者发布答案。)
问题已解决!
输入错误:
COALESCE(@_l_All_Records_Str , ',' , '')
应该是:
COALESCE(@_l_All_Records_Str + ',' , '')
还有最后一个 ,
需要删除(在 ...) + '"],'
中)。
我有一个程序要生成一个由数组组成的类似 JSON 的字符串。
这是我正在使用的查询(以简单的脚本形式呈现):
DECLARE @_l_All_Records_Str VARCHAR(MAX)
SELECT @_l_All_Records_Str = COALESCE(@_l_All_Records_Str , ',' , '') + '["'
+ ISNULL(Time_Unit , '' ) + '","'
+ ISNULL(CAST(Periods AS VARCHAR), '' ) + '","'
+ ISNULL(Details_Present , 'N' ) + '","'
+ ISNULL(Slice_1 , '' ) + '","'
+ ISNULL(Slice_2 , '' ) + '","'
+ ISNULL(Slice_3 , '' ) + '","'
+ ISNULL(Slice_4 , '' ) + '","'
+ ISNULL(Slice_5 , '' ) + '","'
+ ISNULL(Slice_6 , '' ) + '","'
+ ISNULL(Slice_7 , '' ) + '","'
+ ISNULL(Slice_8 , '' ) + '","'
+ ISNULL(Slice_9 , '' ) + '","'
+ ISNULL(Slice_10 , '' ) + '","'
+ ISNULL(Slice_11 , '' ) + '","'
+ ISNULL(Slice_12 , '' ) + '"],'
FROM MyTable ;
SET @_l_All_Records_Str = '[' + @_l_All_Records_Str + ']' ;
print @_l_All_Records_Str ;
结果几乎正确:
[,["M","1","N","Y","Y","Y","N","Y","Y","N","N","Y","Y","Y","N"],["D","","Y","Y","N","N","N","Y","N","N","N","N","N","N","N"],]
从结果中可以看出,有额外的 ,
个字符(一个在开头,另一个在外部数组的末尾)。
有人可以建议我在这里遗漏了什么吗?
(代表问题作者发布答案。)
问题已解决!
输入错误:
COALESCE(@_l_All_Records_Str , ',' , '')
应该是:
COALESCE(@_l_All_Records_Str + ',' , '')
还有最后一个 ,
需要删除(在 ...) + '"],'
中)。