Converting Columns into rows with their respective data in sql server

前端 未结 7 1296
悲哀的现实
悲哀的现实 2020-12-03 17:51

I have a scenario where I need to convert columns of table to rows eg - table - stocks:

ScripName       ScripCode       Price   
--------------------------         


        
7条回答
  •  余生分开走
    2020-12-03 18:06

    As an alternative:

    Using CROSS APPLY and VALUES performs this operation quite simply and efficiently with just a single pass of the table (unlike union queries that do one pass for every column)

    SELECT
        ca.ColName, ca.ColValue
    FROM YOurTable
    CROSS APPLY (
          Values
             ('ScripName' , ScripName),
             ('ScripCode' , ScripCode),
             ('Price'     , cast(Price as varchar(50)) )
      ) as CA (ColName, ColValue)
    

    Personally I find this syntax easier than using unpivot.

    NB: You must take care that all source columns are converted into compatible types for the single value column

提交回复
热议问题