SQL Server触发器包含一个或两个游标

时间:2014-09-19 02:13:25

标签: sql sql-server tsql

我正在尝试在触发器内创建一个游标或游标。我需要做的是当表中的一个字段更新时,我必须迭代一个光标或两个光标并记录表中的所有字段并将旧值和新值插入表中。

这是我目前的代码。此代码正确迭代插入表中的新值,但不会在已删除表中迭代旧值。

ALTER TRIGGER [dbo].[Audit_Emp_Trigger]
   ON  [dbo].[EMPLOYEE]
   AFTER UPDATE, DELETE
AS 
BEGIN
--Set the fields that we will need in this trigger
DECLARE @OldLName NVARCHAR(50);
DECLARE @NewLName NVARCHAR(50);
DECLARE @OldSSN INT;
DECLARE @NewSSN INT;
DECLARE @OldDno INT;
DECLARE @NewDno INT;
DECLARE @Fname NVARCHAR(50);
DECLARE @Mname NVARCHAR(50);
DECLARE @BDate DATE;
DECLARE @Address NVARCHAR(100);
DECLARE @Sex CHAR(1);
DECLARE @Salary INT;
DECLARE @SuperSSN INT;


--Only execute the trigger if the Dno field was updated or deleted
IF UPDATE(Dno)
BEGIN
--If this is an insert operation, we will be inserting a new Dno value

SELECT @OldLName = D.LName FROM deleted D
SELECT @OldSSN = D.Ssn FROM deleted D
SELECT @OldDno = D.Dno FROM deleted D

DECLARE InsertCursor CURSOR FOR SELECT Fname, Minit, Lname, Ssn, Bdate, Address, Sex, Salary, Super_ssn, Dno FROM inserted

OPEN InsertCursor

FETCH NEXT FROM InsertCursor INTO @Fname, @Mname, @NewLName, @NewSSN, @BDate, @Address, @Sex, @Salary, @SuperSSN, @NewDno

WHILE @@FETCH_STATUS = 0

BEGIN

--If the Audit_Emp_Record table does not exist already, we need to create it
IF OBJECT_ID('dbo.Audit_Emp_Record') IS NULL
BEGIN
--Table does not exist in database, so create table
CREATE TABLE Audit_Emp_Record
(
date_of_change smalldatetime,
old_Lname varchar (50),
new_Lname varchar (50),
old_ssn int,
new_ssn int,
old_dno int,
new_dno int
);

--Once table is created, insert the values of the update operation into the table
INSERT INTO Audit_Emp_Record(date_of_change, old_Lname, new_Lname, old_ssn, new_ssn, old_dno, new_dno) VALUES(GETDATE(), @OldLName, @NewLName, @OldSSN, @NewSSN, @OldDno, @NewDno)

END

ELSE
BEGIN
--The table already exists, so simply insert the new values of the update operation into the table
INSERT INTO Audit_Emp_Record(date_of_change, old_Lname, new_Lname, old_ssn, new_ssn, old_dno, new_dno) VALUES(GETDATE(), @OldLName, @NewLName, @OldSSN, @NewSSN, @OldDno, @NewDno)
END

FETCH NEXT FROM InsertCursor INTO @Fname, @Mname, @NewLName, @NewSSN, @BDate, @Address, @Sex, @Salary, @SuperSSN, @NewDno

END

END

END

0 个答案:

没有答案