小编典典

列到SQL Server中的行?

sql

桌子:

CREATE TABLE Table1 (
  col1 INT, 
  col2 nvarchar(10), 
  col3 INT, 
  col4 INT
);

INSERT INTO Table1 
  (col1, col2, col3, col4) 
VALUES 
  (1, 'welcome', 3, 4);

我的表有不同的数据类型,col2是nvarchar h我可以这样做吗?

结果:

col    value
---------------
col1   1
col2   welcome
col3   3
col4   4

阅读 188

收藏
2021-04-07

共1个答案

小编典典

您可以使用该UNPIVOT操作获取结果

SELECT col, value
FROM 
   (SELECT CAST(col1 AS VARCHAR) AS col1, CAST(col2 AS VARCHAR) AS col2,
        CAST(col3 AS VARCHAR) AS col3, CAST(col4 AS VARCHAR) AS col4
   FROM Table1) p
UNPIVOT
   (value FOR col IN 
      (col1, col2, col3, col4)
) AS unpvt;
2021-04-07