亲爱的,我的触发器遇到了麻烦。
我是否正在这样做,现在它只适用于Insert。我想我很亲密,如果你有时间,请帮助我。我试图通过触发器将所有插入,更新和删除存储到表customers_changelog中。我无法删除或更新客户的代码有问题我只能插入新的代码。请帮助我,我已经花了很多时间在这上面,只是不能让这个工作! :)
create table customers (
customerid int identity primary key,
name varchar(100) not null,
address varchar(100)
)
go
create table customers_changelog (
customerid int,
name varchar(100) not null,
address varchar(100),
change_user varchar(32),
change_time datetime,
change_action char(1) default 'I',
check (change_action = 'I' or change_action = 'D')
)
go
CREATE TRIGGER log_changes
ON customers
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
--
-- Check if this is an INSERT, UPDATE or DELETE Action.
--
DECLARE @customerid1 as int;
DEClARE @name1 as varchar(32);
DECLARE @address1 as varchar(100);
DECLARE @change_action1 as char(1);
DECLARE @change_time1 as datetime;
DECLARE @change_user1 as varchar(32);
select @customerid1 = c.customerid, @name1 = c.name, @address1 = c.address
from customers c, inserted i
where c.customerid = i.customerid
SET @change_time1 = CURRENT_TIMESTAMP;
SET @change_user1 = CURRENT_USER;
INSERT INTO customers_changelog(customerid,name,address,change_action,change_time,change_user)
VALUES(@customerid1,@name1,@address1,'I',@change_time1,@change_user1)
IF EXISTS(SELECT * FROM DELETED)
BEGIN
IF EXISTS(SELECT * FROM INSERTED)
INSERT INTO customers_changelog VALUES(@customerid1,@name1,@address1,'U',@change_time1,@change_user1)
ELSE
INSERT INTO customers_changelog VALUES(@customerid1,@name1,@address1,'D',@change_time1,@change_user1)
END
ELSE
IF NOT EXISTS(SELECT * FROM INSERTED) RETURN;
END
答案 0 :(得分:0)
假设MS-SQL来自语法 - 所以这里有几个问题:
1.需要在“更新”和“删除”插入中指定列列表,因为表中的列顺序与您的插入不匹配。
2.不能使用“插入”数据进行删除插入
ALTER TRIGGER [dbo].[log_changes] ON [dbo].[customers] AFTER INSERT, UPDATE, DELETE AS
BEGIN
SET NOCOUNT ON;
DECLARE @customerid1 as int;
DEClARE @name1 as varchar(32);
DECLARE @address1 as varchar(100);
DECLARE @change_action1 as char(1);
DECLARE @change_time1 as datetime;
DECLARE @change_user1 as varchar(32);
select @customerid1 = c.customerid, @name1 = c.name, @address1 = c.address
from customers c, inserted i
where c.customerid = i.customerid
SET @change_time1 = CURRENT_TIMESTAMP;
SET @change_user1 = CURRENT_USER;
IF EXISTS(SELECT * FROM DELETED)
BEGIN
IF EXISTS(SELECT * FROM INSERTED)
INSERT INTO customers_changelog(customerid,name,address,change_action,change_time,change_user)
VALUES(@customerid1,@name1,@address1,'U',@change_time1,@change_user1)
ELSE
BEGIN
select @customerid1 = d.customerid, @name1 = d.name, @address1 = d.address
from deleted d
INSERT INTO customers_changelog(customerid,name,address,change_action,change_time,change_user)
VALUES(@customerid1,@name1,@address1,'D',@change_time1,@change_user1)
END
END
ELSE
BEGIN
IF NOT EXISTS(SELECT * FROM INSERTED) RETURN;
INSERT INTO customers_changelog(customerid,name,address,change_action,change_time,change_user)
VALUES(@customerid1,@name1,@address1,'I',@change_time1,@change_user1)
END
END