我需要创建一个触发器,只要在主表中修改记录,就会将记录添加到队列表中。添加到队列表的记录必须包含为该记录修改的每个字段。
到目前为止我有这段代码,但我认为它不适用于更新的多行:
ALTER TRIGGER [dbo].[tr_EmpHistory]
ON [dbo].[employeeData]
FOR UPDATE
AS
BEGIN
DECLARE @FieldsUpdated xml,
@FieldsUpdated1 varchar(100)
SELECT @Fieldsupdated1 = ' '
SELECT
@FieldsUpdated1 = @FieldsUpdated1 + ' emp_bankaccountnumber'
FROM inserted as a,
deleted as b
WHERE a.emp_id = b.emp_id
AND a.emp_bankAccountNumber <> b.emp_bankAccountNumber
SELECT
@FieldsUpdated1 = @FieldsUpdated1 + 'emp_salary '
FROM inserted as a,
deleted as b
WHERE a.emp_id = b.emp_id
AND a.emp_salary <> b.emp_salary
SELECT
@FieldsUpdated1 = @FieldsUpdated1 + 'emp_SSN '
FROM inserted as a,
deleted as b
WHERE a.emp_id = b.emp_id
AND a.emp_SSN <> b.emp_SSN
SELECT
@FieldsUpdated1 = @FieldsUpdated1 + 'emp_lname '
FROM inserted as a,
deleted as b
WHERE a.emp_id = b.emp_id
AND a.emp_lname <> b.emp_lname
SELECT
@FieldsUpdated1 = @FieldsUpdated1 + 'emp_fname '
FROM inserted as a,
deleted as b
WHERE a.emp_id = b.emp_id
AND a.emp_fname <> b.emp_fname
SELECT
@FieldsUpdated1 = @FieldsUpdated1 + 'emp_manager '
FROM inserted as a,
deleted as b
WHERE a.emp_id = b.emp_id
AND a.emp_manager <> b.emp_manager
SELECT @Fieldsupdated = (
SELECT COLUMN_NAME AS Name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'employeeData'
AND CHARINDEX(COLUMN_NAME,(ltrim(rtrim(@fieldsupdated1)))) > 0
FOR XML AUTO, ROOT('Fields') )
INSERT INTO auditEmployeeData(
audit_emp_id,
audit_emp_bankAccountNumber,
audit_emp_salary,
audit_emp_SSN,
audit_emp_lname,
audit_emp_fname,
audit_emp_manager,
ColumnsUpdated )
SELECT emp_id,
emp_bankAccountNumber,
emp_salary,
emp_SSN,
emp_lname,
emp_fname,
emp_manager,
@FieldsUpdated
FROM INSERTED
END
GO
如果我理解正确,如果一条记录更新了姓氏,而另一条记录同时更新了名字,那么两条记录都将被记录为名字和姓氏都发生了变化。那是对的吗?如果是这样,我怎样才能在不使用光标的情况下使其正常工作?
我能想到解决问题的唯一方法是使用游标,但我知道这不是一个好主意。任何帮助,将不胜感激。
谢谢!