SQL Server : Columns to Rows

后端 未结 6 1139
孤城傲影
孤城傲影 2020-11-22 03:11

Looking for elegant (or any) solution to convert columns to rows.

Here is an example: I have a table with the following schema:

[ID] [EntityID] [Indi         


        
6条回答
  •  无人及你
    2020-11-22 03:25

    I needed a solution to convert columns to rows in Microsoft SQL Server, without knowing the colum names (used in trigger) and without dynamic sql (dynamic sql is too slow for use in a trigger).

    I finally found this solution, which works fine:

    SELECT
        insRowTbl.PK,
        insRowTbl.Username,
        attr.insRow.value('local-name(.)', 'nvarchar(128)') as FieldName,
        attr.insRow.value('.', 'nvarchar(max)') as FieldValue 
    FROM ( Select      
              i.ID as PK,
              i.LastModifiedBy as Username,
              convert(xml, (select i.* for xml raw)) as insRowCol
           FROM inserted as i
         ) as insRowTbl
    CROSS APPLY insRowTbl.insRowCol.nodes('/row/@*') as attr(insRow)
    

    As you can see, I convert the row into XML (Subquery select i,* for xml raw, this converts all columns into one xml column)

    Then I CROSS APPLY a function to each XML attribute of this column, so that I get one row per attribute.

    Overall, this converts columns into rows, without knowing the column names and without using dynamic sql. It is fast enough for my purpose.

    (Edit: I just saw Roman Pekar answer above, who is doing the same. I used the dynamic sql trigger with cursors first, which was 10 to 100 times slower than this solution, but maybe it was caused by the cursor, not by the dynamic sql. Anyway, this solution is very simple an universal, so its definitively an option).

    I am leaving this comment at this place, because I want to reference this explanation in my post about the full audit trigger, that you can find here: https://stackoverflow.com/a/43800286/4160788

提交回复
热议问题