SQL Server:触发AFTER INSERT,UPDATE

时间:2014-11-18 09:14:48

标签: sql-server tsql triggers sql-server-2008-r2

在我的数据库中,我有这个触发器,它可以工作,但它看起来非常糟糕的代码。

当用户注册您的活动时,表格HOURS包含idWork历史记录。每个用户都分配了一个个人idWork

CREATE TRIGGER [dbo].[trg_HOURS_002]
   ON [dbo].[HOURS]
   AFTER INSERT,UPDATE
AS 
BEGIN
    Update [HOURS] 
    set idWork = (select U.idWork 
                  from [USER] U
                  where U.id = (select inserted.idUser from inserted))
     where id = (select inserted.id from inserted)  
END
GO

你能帮助我做得更好吗?

1 个答案:

答案 0 :(得分:1)

尝试将sub-query更改为JOIN。这样的事情。

UPDATE A
SET    idWork = b.idWork
FROM   [HOURS] A
       JOIN (SELECT U.idWork,
                    i.id
             FROM   [USER] U
                    JOIN inserted I
                      ON U.id = i.idUser) B
         ON a.id = b.id 

UPDATE A
SET    idWork = b.idWork
FROM   [HOURS] A
        JOIN inserted I
            ON a.id = I.id
        JOIN [USER] U
            ON U.id = i.idUser