我有幾個問題試圖解決一個SQL觸發器,以自動將用戶設置爲阻止&在另一個表中創建包含日期的塊記錄if其截止日期等於設定的日期。T-SQL插入觸發器插入,在多個表上如果條件更新
問題是,當觸發器被插入關閉時,print語句被執行併發生插入,但插入到表中卻沒有,或者update語句?誰能解釋爲什麼?
注意:insert和Update語句在單獨執行時都可以。
Account表
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表
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
你的觸發將打破。 –