我們有一個用戶表,每個用戶都有一個唯一的電子郵件和用戶名。我們嘗試在我們的代碼中執行此操作,但我們希望確保用戶不會使用相同的電子郵件用戶名在數據庫中插入(或更新)。 我添加了一個BEFORE INSERT
觸發器,它可以防止插入重複的用戶。添加約束以防止SQL更新中的重複觸發
CREATE TRIGGER [dbo].[BeforeUpdateUser]
ON [dbo].[Users]
INSTEAD OF INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @Email nvarchar(MAX)
DECLARE @UserName nvarchar(MAX)
DECLARE @UserId int
DECLARE @DoInsert bit
SET @DoInsert = 1
SELECT @Email = Email, @UserName = UserName FROM INSERTED
SELECT @UserId = UserId FROM Users WHERE Email = @Email
IF (@UserId IS NOT NULL)
BEGIN
SET @DoInsert = 0
END
SELECT @UserId = UserId FROM Users WHERE UserName = @UserName
IF (@UserId IS NOT NULL)
BEGIN
SET @DoInsert = 0
END
IF (@DoInsert = 1)
BEGIN
INSERT INTO Users
SELECT
FirstName,
LastName,
Email,
Password,
UserName,
LanguageId,
Data,
IsDeleted
FROM INSERTED
END
ELSE
BEGIN
DECLARE @ErrorMessage nvarchar(MAX)
SET @ErrorMessage =
'The username and emailadress of a user must be unique!'
RAISERROR 50001 @ErrorMessage
END
END
但是對於更新觸發器,我不知道如何做到這一點。 我發現這個例子與谷歌: http://www.devarticles.com/c/a/SQL-Server/Using-Triggers-In-MS-SQL-Server/2/ 但我不知道它是否適用於一次更新多個列。
編輯:
我試圖在這些列上添加唯一約束,但它不工作:
Msg 1919, Level 16, State 1, Line 1
Column 'Email' in table 'Users' is of a type
that is invalid for use as a key column in an index.
這個問題真的不好冠軍。這個問題沒有關於更新觸發器以及如何使列獨一無二的問題。這個問題不會幫助任何人搜索SQL Update觸發器。 – CodeMonkey 2013-02-06 12:09:46