简体   繁体   中英

Use of COALESCE not giving the desired result in SQL Server

I have a procedure due to generate a JSON-like string which is composed of an array of arrays.

Here is the query I'm using (presented as a simple script):

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 ;

The result is ALMOST correct:

[,["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"],]

As can be seen in the result, there extra , characters (one at the beginning and the other at the end of the outer array).

Would anyone suggest what I'm missing here?

(Posted answer on behalf of the question author.)

Problem resolved!

There was a typo in:

COALESCE(@_l_All_Records_Str , ',' , '')

which should be:

COALESCE(@_l_All_Records_Str + ',' , '')

and also the last , needs to be removed (in ...) + '"],' ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM