如何创建触发器以从另一个表数据更新表

时间:2017-01-03 11:12:00

标签: sql sql-server triggers sql-server-2012

我有一个像这样的表格

ID  |       FROM      |       TO       | day of week
1   |     12/10/2016  |    01/03/2017  |     2
2   |     10/12/2016  |    10/15/2017  |     7
3   |     10/14/2016  |    10/20/2017  |     1
4   |     01/20/2016  |    01/30/2017  |     5
5   |     11/25/2016  |    01/30/2017  |     3
6   |     11/29/2016  |    01/30/2017  |     3

我需要创建一个触发器:在每次插入之后,需要使用插入行的转换来更新另一个表(single_date)。

例如,第一行表示:每周二12/10/2016至01/01/2017

和single_date表应使用以下行进行更新

 ID  | schedule_ID |       date      
 1   |     1       |    12/13/2016  
 2   |     1       |    12/20/2016 
 3   |     1       |    12/27/2016  
 4   |     1       |    01/03/2017 

3 个答案:

答案 0 :(得分:2)

After Insert触发器的代码将帮助您。

Create table Maintable
(
ID int,
FROMD date,
TOD date,
day_of_week int
)

Create table trgTable
(
ID int identity(1,1),
schedule_ID int,
Insdate date 
)


CREATE TRIGGER trgAfterInsert ON Maintable
FOR INSERT
AS  
begin
    DECLARE @MinDate DATE, @MaxDate DATE, @dow int, @id int

    SELECT 
        @MinDate = FROMD, @MaxDate = TOD, @dow = day_of_week, @id = id
    FROM Inserted i

    ;With CTE AS
    (
        SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
                Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
        FROM    sys.all_objects a
                CROSS JOIN sys.all_objects b
    )
    Insert into trgTable
    Select @id, Date from CTE
    Where datepart(dw, Date) = @dow
end

Insert into Maintable values (1, '12-10-2016','01-03-2017', 2)

Select * from Maintable;
Select * from trgTable;

输出:

 ID  | schedule_ID |       insdate      
 1   |     1       |    12-13-2016  
 2   |     1       |    12-20-2016 
 3   |     1       |    12-27-2016  
 4   |     1       |    01-03-2017 

答案 1 :(得分:1)

获得触发器后,可以将此查询用于插入...

with Numbers as
(select 1 as NN
 union all
 select NN + 1
 where NN < 9999
)
insert into single_date (schedule_id, date)
select @schedule_id, dateadd(d,NN, @FromDate)
from Numbers
where datepart(dw,dateadd(d,NN, @FromDate)) = @day_of_week -- This might need converting depending on your DW settings
and dateadd(d,NN, @FromDate) between @From_Date and @To_Date

答案 2 :(得分:-2)

你最好在程序中使用call_back方法更改它。