我有一个小的表(代码如下)与PageKey(int),SendNotification(位)与5个可能PageKeys此刻。而不是更新触发位列
要求是不要有超过1个标志(SendNotification
)同时处于活动状态,所以我想创建一个触发器,当已有另一个pageKey带有活动标志时,不允许将标志更改为True。
我写了下面的触发器,但它似乎没有工作。另外,如果你有任何其他(更好的)解决方案在SQL Server 2012中实现这一点,我会很感激。
CREATE TRIGGER trg_Notification_Flag
ON dbo.t_Notification_Flag
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @countOfExistingFlags INT;
DECLARE @PageKey INT;
SELECT @countOfExistingFlags = COUNT(*)
FROM dbo.t_Notification_Flag
WHERE SendNotification = 1;
SELECT @PageKey = inserted.PageKey
FROM inserted;
IF @countOfExistingFlags > 1
BEGIN
PRINT 'There is an existing active flag. No changes has been done.';
ROLLBACK TRANSACTION;
END;
ELSE
BEGIN
UPDATE dbo.t_Notification_Flag
SET SendNotification = 1
WHERE PageKey = @PageKey;
END;
END;
GO
表是:
CREATE TABLE [dbo].[t_Notification_Flag]
(
[PageKey] [int] NOT NULL,
[SendNotification] [bit] NOT NULL,
[NotificationMessage] [nvarchar](100) NOT NULL,
[NotificationHeader] [nvarchar](50) NULL,
[Country_Key] [int] NULL
) ON [PRIMARY]
你的触发器有一个主要缺陷。它假定插入时只有1个值。每次操作触发器触发一次。此外,您应该小心在触发器内发出回滚。这可能会对具有事务的应用程序造成严重破坏。 –