我正在写一个触发器,我正在使用插入 插入是一行 喜欢
ColumnX |ColumnY|ColumnZ|
=========================
A | B |C |
我想将结果插入另一个像这样的表
ColumnName |Value|
==================
ColumnX | A |
ColumnY | B |
ColumnZ | C |
我有很多表格,我怎么能这样做?
答案 0 :(得分:2)
UNPIVOT
结果集,然后插入它们:
INSERT INTO Anothertable(Columnname, value)
SELECT Columnname, value
FROM tablename t
UNPIVOT
(
value
FOR ColumnName IN(ColumnX, ColumnY, ColumnZ)
) AS u;
为此dymaincally:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(Columnname)
FROM table1 t
UNPIVOT
(
value
FOR ColumnName IN(ColumnX, ColumnY, ColumnZ)
) AS u
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SET @query = 'SELECT Columnname, value
FROM table1 t
UNPIVOT
(
value
FOR ColumnName IN( ' + @cols + ' )
) AS u;'
execute(@query);
答案 1 :(得分:0)
CREATE TRIGGER TriggerName
ON YourDatabase.TableName
AFTER INSERT
AS
BEGIN
INSERT INTO OtherTable (ColumnX, ColumnY, ColumnZ)
SELECT ColumnX, ColumnY, ColumnZ
FROM inserted
END
GO