求一SQL触发器
单据分为表头SC_Head,表体SC_Body,表头中有字段id,cVenCode,表体中有字段id,dArrDate,dStartDate,两个表通过id关联。我想要的结果是在新增单据保存时,判断当表头中的cVenCode字段等于02002-001时,表体中dStartDate日期字段等于输入的日期dArrDate字段减去4天。
请问各位大神能否用触发器实现。
[解决办法]
用存储过程更好
[解决办法]
触发器建立在SC_Body上,
核心代码大致如下:
declare id int = (select id from inserted)
declare dArrDate Date = (select dArrDate from inserted)
declare dStartDate Date = (select dStartDate from inserted)
if((select cVenCode from SC_Head where ID = id) = '02002-001')
begin
insert SC_Body
select id, dArrDate, DateAdd(Day, -4, dArrDate)
end
else
begin
insert SC_Body
select id, dArrDate, dArrDate
end
[解决办法]
--#1.先插入表体表
--#2.再插入表头表
--#3.触发表头表中的触发器
CREATE TRIGGER tr_test ON dbo.SC_Head
AFTER INSERT
AS
BEGIN
UPDATE B
SET B.dArrDate = DATEADD(DAY, -4, dArrDate)
FROM INSERTED I
INNER JOIN SC_Body B
ON I.id = B.id
WHERE I.cVenCode = '02002-001'
END
--#1.先插入表头表
--#2.再插入表体表
--#3.触发表头体中的触发器
CREATE TRIGGER tr_test ON dbo.SC_Body
AFTER INSERT
AS
BEGIN
UPDATE A
SET A.dArrDate = DATEADD(DAY, -4, A.dArrDate)
FROM INSERTED I
INNER JOIN SC_Body A
ON I.id = A.id
INNER JOIN SC_Head B
ON I.id = B.id
WHERE B.cVenCode = '02002-001'
END