Coalesce will return the first non-null value among its arguments documentation says. I can also use it like below:

DECLARE @ColumnValue VARCHAR(MAX);
SELECT @ColumnValue = COALESCE(@ColumnValue+',','') + ColumnValue
FROM dbo.TableA
SELECT @ColumnValue

According to my understanding, there should be a , at the very front of the output list since at the very beginning there will at least be a comma passed as an argument. Also, if I put some value in the second argument. It appears at the very front instead of the , as I expected.

If someone can please explain the code to me. I will be very grateful.

有帮助吗?

解决方案

Your understanding is not correct.

Focus on the expression:

SELECT @ColumnValue = COALESCE(@ColumnValue+',','') + ColumnValue
-------------------------------^XXXXXXXXXXXXXXX

The first argument to COALESCE() is @ColumnValue+','. This is NULL initially, so it gets replaced by ''. Then comes ColumnValue as the first element in the list.

You are likely thinking of:

SELECT @ColumnValue = COALESCE(@ColumnValue, '') + ',' + ColumnValue

其他提示

You are confused. Since at first @ColumnValue is NULL, then the result of @ColumnValue + ',' is also NULL, so the result of COALESCE(@ColumnValue+',','') is ''. This is easily tested with:

DECLARE @ColumnValue VARCHAR(MAX);

SELECT COALESCE(@ColumnValue+',','')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top