简体   繁体   中英

Understanding TSQL and COALESCE to have dynamic columns in a PIVOT

I had asked a similar question yesterday but still don't have a basic understanding of why this logic works. I'm getting the right outupt and I'm happy with that, but why does it work the way it does?

Say for instance we're using this simple query:

    create table #TestTable (FakeColumn varchar(50))
    INSERT INTO #TestTable (FakeColumn) VALUES ('ABC'),('DEF'),('GHI'),('JKL')

    DECLARE @columns VARCHAR(8000)

  SELECT @columns = COALESCE(@columns + ',[' + cast(FakeColumn as varchar) + ']',
  '[' + cast(FakeColumn as varchar)+ ']')
  FROM #TestTable
  GROUP BY FakeColumn

      select @columns

      drop table #TestTable

The output of the following query is: [ABC],[DEF],[GHI],[JKL] which happens to be exactly what I need... but lets say we modified the query to read:

 SELECT @columns = '[' + cast(FakeColumn as varchar)+ ']'
 FROM #TestTable
 GROUP BY FakeColumn

 select @columns
  1. Why is my output now: [JKL] ?

And now if we modify the COALESCE to only include the first argument [with the @columns appended to the front]

  SELECT @columns = @columns + ',[' + cast(FakeColumn as varchar) + ']'
        FROM #TestTable
  GROUP BY FakeColumn
  1. Why is my output now: NULL ?

It looks as if my first value in that COALESCE statement returns NULL, therefore it should go to my second statement but that's only returning [JKL] ... however, with both of them combined I get the string that I need... I'm not sure how this works, or why it does. Can anyone help explain this to a rookie?

1.Why is my output now: [JKL]?

This is easy. You have a group by in the query, so it is returning multiple rows. Only one row provides the assignment to the variable. Which row is arbitrary.

1.Why is my output now: NULL?

This is easy. The variable @columns is initialized to NULL . Concatenating anything to NULL produces NULL .

 SELECT @columns = @columns + ',[' + cast(FakeColumn as varchar) + ']'
       FROM #TestTable
 GROUP BY FakeColumn

Your value here is null because you declared @column without any value before the select, so the initial value is NULL. Everything added to a NULL varchar, will result in a NULL result

COALESCE returns the first not NULL value.

The first argument in the COALESCE below will return a NULL, because anything added to a NULL value, is by default NULL (your @columns variable is NULL). So first it will return the second part, and there after it will add the first part in the COALESCE when @columns have a value

 SELECT @columns = COALESCE(@columns + ',[' + cast(FakeColumn as varchar) + ']',
 '[' + cast(FakeColumn as varchar)+ ']')
 FROM #TestTable
 GROUP BY FakeColumn

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