我创建了一个表tblAddress
,我想使用一个触发器。当我INSERT/DELETE
或UPDATE
时,这些更改应保存在另一个表中 - 在锁定表中。我是SQL Server的初学者,能帮助我解决这个问题吗?
我刚做了这么多。我想要存储触发器信息的另一个表名为tr_Lock
。
Create Trigger tr_tblAddress_ForInsertDeleteUpdate
On tblAddress
After Insert,Delete,Update
As
Print 'You Deleted, Inserted, Updated one row from tblAddress';
答案 0 :(得分:0)
这是您案例的样本数据
CREATE TABLE BILL (BILL_NBR INT IDENTITY PRIMARY KEY, BILL_NME VARCHAR(50),CREATE_DTE DATETIME, MODIFY_DTE DATETIME)
GO
CREATE TABLE LOG_BILL (LOG_BILL_NBR INT IDENTITY PRIMARY KEY, LOG_DTE DATETIME, BILL_NBR INT, BILL_NME VARCHAR(50)
,CREATE_DTE DATETIME, MODIFY_DTE DATETIME)
GO
CREATE TRIGGER [dbo].[TRG_BILL_LOG] ON [dbo].BILL
AFTER UPDATE,DELETE
AS
INSERT INTO LOG_BILL (LOG_DTE,BILL_NBR,BILL_NME,CREATE_DTE,MODIFY_DTE)
SELECT I.MODIFY_DTE, D.BILL_NBR, D.BILL_NME, D.CREATE_DTE, D.MODIFY_DTE FROM DELETED D
LEFT JOIN INSERTED I ON D.BILL_NBR = I.BILL_NBR
GO
INSERT INTO BILL
SELECT 'A',GETDATE(), GETDATE()
GO
UPDATE BILL SET BILL_NME='B' WHERE BILL_NBR=1
GO
SELECT * FROM LOG_BILL
答案 1 :(得分:0)
每个语句触发一次,而不是每行一次。触发器可以访问插入的,已删除的表,您可以根据自己的要求使用这些表。
插入后可以访问新插入的行,删除后可以访问已删除的行,更新后可以访问已删除的行以及新更新的行。
请参阅下面的简单示例
create table triggertest
(
id int,
name char(1)
)
create table log
(
id int,
name char(1),
operationdone char(2),
loggedtime datetime
)
Alter trigger trg_test1
on triggertest
after insert,update,delete
as
begin
set nocount on
--insert updated rows
if exists(select 1 from inserted) and exists(select 1 from deleted)
begin
insert into log
select *,'U',getdate() from inserted
return
end
----insert new rows
if exists(select 1 from inserted)
begin
insert into log
select *,'I',getdate() from inserted
return
end
--insertd deleted rows
if exists(select 1 from deleted)
begin
insert into log
select *,'D',getdate() from deleted
return
end
end
insert into triggertest
select 1,'z'
update triggertest
set
id=2
where name='z'
delete from triggertest
select * from log
select * from triggertest
id name operationdone loggedtime
1 z I 2016-03-08 19:54:23.617
2 z U 2016-03-08 19:54:30.373
2 z U 2016-03-08 19:54:30.373
2 z D 2016-03-08 19:54:39.063
2 z D 2016-03-08 19:54:39.063
答案 2 :(得分:0)
以下是设置触发器以便插入,更新和删除
的示例Objetive-C