更新触发后&级联

时间:2017-07-18 14:07:35

标签: tsql

我之前没有使用过触发器,所以这是一个“工作”的工作'首先刺中我需要达到的目标。 一旦我进入价值观' V'或者' AV'在VCODE字段中,触发器填充VSYS,SITE_CODE,VAREA&所需的值。然后将这些值连接到ASSET_TAG字段。

我不认为这是执行此操作的最有效方式,因此有人可以在SQL版本中查看我的杂乱脚本,并建议最有效的方法来实现相同的结果。

由于

Trigger [dbo].[trValve]    
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create trigger [dbo].[trValve] on [dbo].[Valve]
after update
as

Begin
set nocount on;
update Valve Set VSYS = 'VLV'
from Valve t  
inner join inserted i on  t.pkID = i.pkID 
and i.VCODE='V' or 
i.VCODE = 'AV'

Begin
set nocount on;
update Valve 
Set SITE_CODE = '00123'
from Valve t  
inner join inserted i on  t.pkID = i.pkID 
and i.VCODE='V' or 
i.VCODE = 'AV'

Begin
set nocount on;
update Valve 
Set VAREA = 'INL'
from Valve t  
inner join inserted i on  t.pkID = i.pkID 
and i.VCODE='V' or 
i.VCODE = 'AV'

Begin
set nocount on;
update VALVE 
SET ASSET_TAG = CONCAT(Valve.SITE_CODE,'-',Valve.VAREA,'-',   valve.VSYS,'-',Cast (pkID As Varchar(50)));


End 
End
End
End
End

1 个答案:

答案 0 :(得分:0)

您可以通过组合前3个SET语句来缩小一些内容:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[trValve] ON [dbo].[Valve]
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Valve
    SET VSYS = 'VLV',
    SITE_CODE = '00123',
    VAREA = 'INL'
    FROM Valve t
    INNER JOIN inserted i ON t.pkID = i.pkID
    WHERE i.VCODE = 'V'
    OR i.VCODE = 'AV'

BEGIN
    SET NOCOUNT ON;

    UPDATE VALVE
    SET ASSET_TAG = CONCAT (
            Valve.SITE_CODE,'-',Valve.VAREA,'-',valve.VSYS,'-',Cast(pkID AS VARCHAR(50))
            );
END
END