我有一个表变量,它包含表的键,值对的记录。其中key是表的列,value是该列的值
下面是表变量
DECLARE @Table TABLE(
FieldName varchar(100),
FieldValue varchar(max))
insert into @Table values('Title','NewFrom')
insert into @Table values('Points','4')
insert into @Table values('createdby','5')
我在UsersInformation中有以上值。这是sql server的物理表 有以下专栏。
UserID int autoincrement(identity)
Title nvarchar(100),
Points int,
createdby int
我希望@Table的所有值都应该是UserInformation表的一行。
如何使用sql server?
答案 0 :(得分:0)
尚未测试,但这应该有效
INSERT INTO UsersInformation (Title, Points, createdby)
SELECT Title, Points, createdby FROM (SELECT FieldName, FieldValue
FROM @Table) AS SourceTable
PIVOT (MAX(FieldValue) FOR FieldName IN ([Points], [Title], [createdby])) AS PivotTable;
根据您的评论,您需要在源@table
中添加一个密钥DECLARE @Table TABLE(
id int,
FieldName varchar(100),
FieldValue varchar(max))
insert into @Table values(1,'Title','NewFrom')
insert into @Table values(1,'Points','4')
insert into @Table values(1,'createdby','5')
insert into @Table values(2,'Title','NewFrom2')
insert into @Table values(2,'Points','44')
insert into @Table values(2,'createdby','55')
insert into @Table values(3,'Title','NewFrom3')
insert into @Table values(3,'Points','444')
然后您可以运行查询:
SELECT [Title], [Points], [createdby]
FROM @Table
PIVOT
(
max(FieldValue) FOR [FieldName] IN ([Title], [Points], [createdby])
) AS P