Search code examples
sqlsql-serversql-server-2008-r2unpivot

SQL: Turn a row into a column (and include column names in a new column)


I'm busy writing a claims provider class to be used in a Security Token Service.

User permissions are read from a SQL Server 2008 R2 database:

SELECT A, B, C, ..., X FROM Permissions WHERE UserId = @UserId

would give me a single row, for example:

A B C ... X
1 0 1     1

it would be much easier to have this data in the form

Permission Value
A          1
B          0
C          1
...
X          1

Since the actual table contains dozens of columns, I'd prefer to be able to do the transposition "dynamically" without really having to type up any column names by hand.

It feels like the PIVOT/UNPIVOT functions and INFORMATION_SCHEMA.COLUMNS view are what I need, but I can't quite figure out what to do.

Any ideas for a query that would do this?

PS. I guess if push comes to shove, I'd just stick the result set in a DataTable and iterate over the columns in code to generate the user claims, but I'd like to find out if the above approach is possible first :)


Solution

  • If you do not have an UNPIVOT function available (you did not specify RDBMS) then you can use UNION ALL (See SQL Fiddle with Demo):

    select 'A' as Permission, A as Value
    FROM Permissions
    WHERE UserId = @UserId
    UNION ALL
    select 'B' as Permission, B as Value
    FROM Permissions
    WHERE UserId = @UserId
    

    If you have an unknown number of columns in sql-server, then you can use dynamic sql and your code would be similar to this:

    DECLARE @colsUnPivot AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    SET @colsUnPivot = stuff((select ','+C.name
             from sys.columns as C
             where C.object_id = object_id('Permissions')
                and C.name != 'UserId'
             for xml path('')), 1, 1, '')
    
    set @query 
      = 'select permission, value
        from
        (
            select *
             from permissions
             where userid = '+@UserId+'
        ) x
         unpivot
         (
            value
            for permission in ('+ @colsunpivot +')
         ) u'
    
    exec(@query)
    

    see SQL Fiddle with Demo