简体   繁体   中英

Insert into a table having a sub-select?

I have this audit table:

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

And I have this trigger:

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')

How can I insert records in the audit table where item_id must be the id column from either inserted or deleted and the history column should contain the xml for that particular record.

So you mean this?:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM