有很多,你需要看的東西。 MSSQL不支持觸發器之前或逐行觸發器(因此您不能使用新的或舊的結構),並且您必須使用遊標來逐行模擬行觸發器。
爲了給你一個開始,這裏給出了一個更新後的觸發器,用戶將新舊值寫入錯誤表。
USE [Sandbox]
GO
/****** Object: Table [dbo].[users] Script Date: 25/04/2017 16:01:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[users](
[user_id] [int] NULL,
[contact_type_id] [int] NULL,
[value] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
user_id contact_type_id value
----------- --------------- --------------------
1 2 aaa
1 3 aaa
2 1 [email protected]
3 1 [email protected]
3 2 123345
3 3 skypeLogin2
(6 row(s) affected)
--drop trigger tai_users
CREATE TRIGGER TAI_users
on users
after update
AS
BEGIN
declare old cursor for select value from deleted
declare new cursor for select value from inserted
declare @oldvalue as varchar(20)
declare @newvalue as varchar(20)
open old
open new
fetch next from old into @oldvalue
fetch next from new into @newvalue
insert into errors (msg) values (concat(@oldvalue,',',@newvalue))
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM old INTO @oldvalue
fetch next from new into @newvalue
insert into errors (msg) values (concat(@oldvalue,',',@newvalue))
END
close old
close new
deallocate old
deallocate new
END
--truncate table errors
update users
set value = 'bbb'
where user_id = 1
select * from errors
select * from users
2 aaa,bbb
3 aaa,bbb
4 aaa,bbb
(4 row(s) affected)
user_id contact_type_id value
----------- --------------- --------------------
1 2 bbb
1 3 bbb
2 1 [email protected]
3 1 [email protected]
3 2 123345
3 3 skypeLogin2
你有什麼試過的?不要指望我們做你的工作......但是如果遇到特定問題,我們可以提供幫助! – jarlh
我沒有什麼好主意,因爲「之前改爲」在MSSQL中是不可能的。而是用以下方式初始化一個變量:我必須使用@ - >這是正確的嗎? – Joseph