gpt4 book ai didi

sql-server - SQL Server 中的插入/删除/更新触发器

转载 作者:行者123 更新时间:2023-12-01 22:13:14 24 4
gpt4 key购买 nike

我正在尝试生成一个一体化的删除/插入/更新触发器。我在第二个和第三个 AFTERS 附近出现两个“语法错误”,在最后一个 END 附近出现语法错误。

CREATE TRIGGER trig_all_dml
ON [dbo.file]
AFTER UPDATE
AS BEGIN
UPDATE
(excess code)
END

AFTER INSERT
AS BEGIN
UPDATE
(excess code)
END

AFTER DELETE
AS BEGIN
UPDATE (excess code)

END
GO

希望这是足够的信息。我认为问题出在我的语法上,但我在网上找不到正确的语法。

最佳答案

我给你的是插入、更新和删除触发器的代码这在 Microsoft SQL SERVER 2008 及更高版本上运行良好我使用的数据库是 Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
EmpID int,
Activity varchar(20),
DoneBy varchar(50),
Date_Time datetime NOT NULL DEFAULT GETDATE()
);

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
SET @activity = 'UPDATE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
SET @activity = 'INSERT';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin
SET @activity = 'DELETE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from deleted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

关于sql-server - SQL Server 中的插入/删除/更新触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20205639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com