插入具有子选择的表格?

时间:2015-03-16 12:49:40

标签: sql sql-server sql-server-2014

我有这个审核表:

create table audit(
    id int IDENTITY(1, 1) NOT NULL,
    item_id int NOT NULL,
    history text NOT NULL,
)

我有这个触发器:

create trigger tr_mytable_audit ON mytable after insert, update, delete
as
select *
from inserted as i
  full join deleted as d
    on i.id = d.id
for xml path('row'), root('rows')

如何在审核表中插入记录,其中item_id必须是idinserted的{​​{1}}列,且deleted列应包含该特定记录的xml。

1 个答案:

答案 0 :(得分:0)

你的意思是这个?:

create trigger tr_mytable_audit ON mytable after insert, update, delete
as
INSERT INTO audit(item_id, history)
SELECT i1.id, (
 select *
 from inserted as i
  full join deleted as d
    on i.id = d.id
 where i.id=i1.id
 for xml path('row'), root('rows')
)
from inserted i1
UNION 
SELECT i1.id, (
 select *
 from inserted as i
  full join deleted as d
    on i.id = d.id
 where d.id=d1.id
 for xml path('row'), root('rows')
)
from deleted d1