我有一个表,其中包含一些字段和值。我正在尝试获取表列名称和值(列名-值对)的列表。
例如,我在下表中包含字段和值:
MyTable:
Field1 Field2 Field3 .... FieldN
89 34 10 233
所以我想得到下表(字段名-字段值对):
FieldName FieldValue
Field1 89
Field2 34
Field3 10
...
FieldN 233
我的意思是一个有两个字段的表:FieldName作为文本,FieldValue作为数字。
要获取表列名称的列表,请执行以下操作:
SELECT NAME FROM sys.columns WHERE object_id = OBJECT_ID('schema.MyTable')
但是我不知道如何获取每个列名的值。我该怎么办?
答案 0 :(得分:0)
您必须使用动态查询来动态使用列,并且需要使列的大小相同以解决问题Column conflicts with the type of other columns in the unpivot list
。我发现它非常乏味,尽管对您而言非常有用
CREATE TABLE test (Field1 INT, Field2 INT, Field3 INT, FieldN INT, flag CHAR(1))
INSERT INTO test VALUES
(89,34,10,233, 'i')
DECLARE @sql NVARCHAR(MAX) = N'',
@colIn NVARCHAR(MAX) = N'',
@colSelect NVARCHAR(MAX) = N''
SELECT
@colIn += ', ' + QUOTENAME(name),
@colSelect += ',' + QUOTENAME(name) + ' = CONVERT(VARCHAR(255), ' + QUOTENAME(name) + ')'
FROM sys.columns
WHERE object_id = OBJECT_ID('test')
SET @sql = '
SELECT a.FieldName, a.FieldValue
FROM (SELECT ' + STUFF(@colSelect, 1, 1, '') + '
FROM test) t
UNPIVOT([FieldValue] FOR [FieldName] IN (' + STUFF(@colIn, 1, 1, '') + ')) a '
EXEC(@sql)
输出:
FieldName FieldValue
Field1 89
Field2 34
Field3 10
FieldN 233
flag i
答案 1 :(得分:0)
一种可能的方法是使用UNPIVOT
生成动态语句。如果您的列来自不同的数据类型,请使用CONVERT
:
输入:
CREATE TABLE Data (
ColumnVarchar varchar(100),
ColumnDateTime datetime,
ColumnInt int
)
INSERT INTO Data
(ColumnVarchar, ColumnDateTime, ColumnInt)
VALUES
('Some text 1', GETDATE(), 1)
声明:
-- Declarations
DECLARE @stm nvarchar(max)
DECLARE @names nvarchar(max)
DECLARE @values nvarchar(max)
-- Dynamic part
SELECT
@values = STUFF((
SELECT CONCAT(N', CONVERT(varchar(max), ', QUOTENAME([COLUMN_NAME]), N') AS ', QUOTENAME([COLUMN_NAME]))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Data'
FOR XML PATH('')
), 1, 1, N''),
@names = STUFF((
SELECT CONCAT(N', ', QUOTENAME([COLUMN_NAME]))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Data'
FOR XML PATH('')
), 1, 1, N'')
-- Whole statement and execution
SELECT @stm =
CONCAT(
N'SELECT u.FieldName, u.FieldValue FROM (SELECT',
@values,
N'FROM Data) d UNPIVOT ([FieldValue] FOR [FieldName] IN (',
@names,
N')) u')
EXEC (@stm)
输出:
-----------------------------------
FieldName FieldValue
-----------------------------------
ColumnVarchar Some text 1
ColumnDateTime Apr 29 2019 1:45PM
ColumnInt 1
更新-将结果保存到其他表中:
-- Whole statement and execution
SELECT @stm =
CONCAT(
N'SELECT u.FieldName, u.FieldValue INTO ResultTable FROM (SELECT',
@values,
N'FROM Data) d UNPIVOT ([FieldValue] FOR [FieldName] IN (',
@names,
N')) u')
EXEC (@stm)
SELECT *
FROM ResultTable