创建而不是插入触发器SQL

时间:2016-03-17 15:12:35

标签: sql sql-server

我是公司的DBA。我试图创建触发器,将首先检查任何插入语句的重复项,如果没有允许原始插入。甚至不确定这可以做到。 insert语句可以由各种用户编写,因此语句永远不会相同。到目前为止我找到的只是检查重复项,但插入语句然后在触发器中进行了硬编码。我的计划也是检查更新,但现在不重要。

这是我目前的代码。

ALTER TRIGGER [dbo].[BlockDuplicatesOnTable]
ON [dbo].[blockduplicates]
Instead of INSERT, Update
AS
BEGIN
SET NOCOUNT ON;


Declare @ProviderAcctNumber nvarchar(50)
Declare @Referredby int

Declare @Action as char(1)
Declare @Count as int
Set @Action = 'I'
Select @Count = Count(*) from DELETED
IF @Count > 0
Begin
Set @Action = 'D'
Select @Count = count(*) from INSERTED
IF @Count > 0
Set @Action = 'U'

    IF @Action = 'I'

    Begin
    IF not exists (Select 1 from inserted as i
    inner join dbo.blockduplicates as b
    on i.ProviderAcctNumber = b.ProviderAcctNumber
        and i.Referredby = b.Referredby)
    Begin
        --execute original insert
    End
    Else 
    Begin
        Print 'Duplicate insert'
        Raiserror ('Duplicate Entry for Insert',16,1);
        Return
    End
    End
Else IF @Action = 'U'

Begin

Select @ProviderAcctNumber = ProviderAcctNumber, @Referredby = Referredby from inserted
IF Not exists (Select 1 from deleted where ProviderAcctNumber = @ProviderAcctNumber and Referredby = @Referredby)
    Begin
        Print 'Update Statement is True';
    End
    Else 
    Begin
        Print 'duplicate'
        Raiserror ('Duplicate Entry for Update',16,1);
        Return
    End
End
End
End;

0 个答案:

没有答案