T-SQL插入触发器在多个表上插入,更新if条件

时间:2012-12-15 23:54:30

标签: sql sql-server triggers insert updates

我在尝试解决SQL触发器以自动将用户设置为阻止&时遇到一些问题。如果其截止日期等于设定日期,则在另一个表中创建包括日期的块记录。

问题在于,当插入触发器触发时,执行print语句并发生插入,但是插入到表中没有,或者更新语句?任何人都可以解释原因吗?

注意:insert和Update语句在自己执行时都可以。

帐户表

CREATE TABLE [dbo].[Account](
[AccountNo] [int] IDENTITY(1,1) NOT NULL,
[CustomerNo] [int] NOT NULL,
[PaymentNo] [int] NULL,
[CreditNo] [int] NULL,
[BlockID] [dbo].[number] NULL,
[Balence] [dbo].[currency] NOT NULL,
[AmountDue] [dbo].[currency] NOT NULL,
[DueDate] [dbo].[dates] NULL,
[AutherisedBy] [nvarchar](50) NOT NULL,
[DateCreated] [date] NOT NULL,

BLOCKEDUSER TABLE

CREATE TABLE [dbo].[BlockedUsers](
[BlockID] [int] IDENTITY(1,1) NOT NULL,
[DateEnforced] [dbo].[dates] NOT NULL,
[Blocked] [dbo].[switch] NOT NULL,

TRIGGER

ALTER TRIGGER [dbo].[Add_Blocked_User]
ON [dbo].[Account]
FOR INSERT
AS  
BEGIN
SET NOCOUNT ON;

Declare @ID int
Select @ID = [AccountNo] from inserted  
If(Select [DueDate] from inserted) = '2011-01-01'

INSERT INTO dbo.BlockedUsers(DateEnforced,Blocked)
VALUES (GETDATE(),1)
PRINT 'New Block Date Added'

UPDATE Account 
Set BlockID = IDENT_CURRENT('BlockID')
where @ID = @ID
PRINT 'Account Blocked'

END

GO

完全正常工作示例:使用下面的帮助完成。

ALTER TRIGGER [dbo].[Add_Blocked_User]
ON [dbo].[Account]
AFTER INSERT
AS 
BEGIN

SET NOCOUNT ON;

Declare @ID int
Select @ID = [AccountNo] from inserted  
 If(Select [DueDate] from inserted)Not Between (select CONVERT(date, getdate() - 30)) And (select CONVERT(date, getdate()))
Begin
    INSERT INTO dbo.BlockedUsers(DateEnforced,Blocked)
    VALUES (GETDATE(),1)
    PRINT 'New Block Date Added'

    UPDATE Account 
    Set BlockID = (Select Max(BlockID) From BlockedUsers)
    where [AccountNo] = (Select [AccountNo] from inserted)  
    PRINT 'Account Blocked'
 End

 END

GO

2 个答案:

答案 0 :(得分:5)

Transact-SQL中的IF语句需要在条件之后的单个语句:

IF condition
  statement;

如果要在同一分支中执行多个语句,则必须将它们括在BEGIN / END“括号”中:

IF condition
BEGIN
  statement;
  statement;
  ...
END;

在触发器中,只有INSERT语句执行,具体取决于(Select [DueDate] from inserted) = '2011-01-01'条件的结果。对于PRINT和UPDATE,它们无条件地执行,即在每个插入Account之后。因此,您可能需要在INSERT,UPDATE和两个PRINT周围添加BEGINEND

...
If(Select [DueDate] from inserted) = '2011-01-01'
BEGIN
INSERT INTO dbo.BlockedUsers(DateEnforced,Blocked)
VALUES (GETDATE(),1);
PRINT 'New Block Date Added';

UPDATE Account 
Set BlockID = IDENT_CURRENT('BlockID')
where @ID = @ID;
PRINT 'Account Blocked';
END;
...

答案 1 :(得分:-2)

你做了

FOR INSERT

您想要使用

AFTER INSERT, UPDATE

FOR INSERT告诉Sql Server你的触发器将完全取代正常的插入操作。 AFTER INSERT告诉Sql Server继续插入行,然后执行此代码作为后处理步骤。