一行插入MS SQL后INSERT和UPDATE

时间:2014-06-17 23:19:31

标签: sql-server triggers insert where

我不知道我的想法是否正确,所以我愿意接受建议。 我正在使用MS SQL SERVER 2008 R2。 这是'故事' 每当有人在tblDelivered中插入一行时,就会有一个触发器在tblConditionDel中插入五个值(1,1,1,1,1)。这是一个具有自动ID增量的表。对于插入的行,必须使用来自tblConditionDel的ID更新fieldname ConditionID。 我认为我的where声明有问题 如果我删除了where语句,那么整个表的ID都是更新的,但它必须是一个插入的行。

我的代码:

ALTER TRIGGER [dbo].[trgCond2] ON [dbo].[tblDelivered] 
    AFTER INSERT
AS 
insert into tblConditionDel(Con1,Con2,Con3,Con4, Con5)
values(1,1,1,1,1);

update tblDelivered set ConditionID = (select max(ConditionID) from tblConditionDel)
where (select 1 from inserted) = tblDelivered.ConditionID

提前谢谢

2 个答案:

答案 0 :(得分:1)

如果插入了多行,您的解决方案将无效。

这样做

CREATE TABLE tblDelivered (
    DeliveredID int NOT NULL
   ,ConditionID int
);

CREATE TABLE tblConditionDel (
    ConditionID int IDENTITY(1,1)
   ,Con1 int NOT NULL
   ,Con2 int NOT NULL
   ,Con3 int NOT NULL
   ,Con4 int NOT NULL
   ,Con5 int NOT NULL
);

CREATE TRIGGER [dbo].[trgCond2] ON [dbo].[tblDelivered] 
    AFTER INSERT
AS 
    SET NOCOUNT ON;

    DECLARE @ConditionIDs AS table ( -- stores inserted conditionsIDs
        DeliveredID int NOT NULL
       ,ConditionID int NOT NULL
    );

    MERGE INTO tblConditionDel -- INSERT does not support OUTPUT INTO for multiple rows
    USING inserted AS triggerinserted
        ON 1 = 0
    WHEN NOT MATCHED THEN
        INSERT (Con1, Con2, Con3, Con4, Con5)
        VALUES (1,1,1,1,1)
    OUTPUT triggerinserted.DeliveredID
          ,inserted.ConditionID
    INTO @ConditionIDs;

    UPDATE tblDelivered
    SET ConditionID = ConditionIDs.ConditionID
    FROM tblDelivered
         INNER JOIN @ConditionIDs AS ConditionIDs
             ON ConditionIDs.DeliveredID = tblDelivered.DeliveredID

-- Test code
INSERT INTO tblDelivered (DeliveredID)
VALUES (4),(5),(6);

SELECT * FROM tblConditionDel
SELECT * FROM tblDelivered

答案 1 :(得分:0)

你会想做这样的事情:

ALTER TRIGGER [dbo].[trgCond2] ON [dbo].[tblDelivered] 
    AFTER INSERT
AS 
declare @new_id int, @delivered_id int

set @delivered_id = (select ConditionID from inserted) -- captures id from inserted table

insert into tblConditionDel(Con1,Con2,Con3,Con4, Con5)
values(1,1,1,1,1);

set @new_id = scope_identity() -- captures new id from tblCondition into a variable

update tblDelivered set ConditionID = @new_id -- set new tblcondition id
where ConditionID = @delivered_id -- for the record that matches the inserted one