如何将一行数据合并到sql server

时间:2017-07-05 18:42:55

标签: sql sql-server sql-server-2016

我有一个这样的触发器:

alter trigger newTrigger
on table2
after insert 
as
begin
    declare @rowData nvarchar(max)
    if exists(select * from inserted)
    begin
        Set @rowData = (select * from inserted)
    end

    insert into table1(rowData, date)
    values(@rowData, getdate())
end

我希望在插入到table2之后,将插入的记录和日期插入到table1中 但我不能将行数据合并为一列!

------------------table2--------------------
id   |  name  |   lname  | birth
1        j          jj       2000-03-03


-------------------table1 after insert into table2 -----------------
rowData            |     date
a,j,jj,2000-03-03       2017-05-07

1 个答案:

答案 0 :(得分:2)

您必须进行转换并逐列添加

例如:

Set @rowData = (select cast(col1 as varchar(10)) + cast(col2 as varchar(10)) from inserted)

使用列名进行编辑。如果列已经是varchar,那么唯一需要注意的是避免长度溢出:

Set @rowData = (select cast((id + ',' + name + ',' + lname + ',' + cast(birth as varchar(12)) ) as varchar(4000))  from inserted)