使用触发器创建每日日志表

时间:2019-03-01 13:42:29

标签: sql sql-server database

我有一个查询,查询的结果存储在一个表中。

select id, name, category, date1, count1,count2, count3
into stage
from table1 t1 join table2 t2 on t1.is =t2.id join table3 t3 on t2.id = t3.id

该查询的结果必须每天存储在新的日志表中,并添加一个附加的日期字段以捕获其记录的日期时间。 我该如何创建呢?

1 个答案:

答案 0 :(得分:1)

您可以通过触发器来执行此操作,但是不能重新创建表阶段,因为每次重新创建它(使用in)时,都会丢失触发器。试试这个模式:

create table t21 (i1 int) -- source table
create table t21s (i1 int) -- stage table
create table t2log(i1 int, when1 datetime); -- log table
go
;
create trigger t_t21s on t21s after insert
as
set nocount on
insert into t2log(i1, when1)
select inserted.i1,getdate() 
    from inserted;


    insert into t21 values (5)
    -- every day or whenever you want to fill the staging table
    truncate table t21s -- every day or period
    insert into t21s (i1) -- fill up stage table without destroying trigger

    select * from t21 -- see what is in stage

    select * from t2log -- see what is in log