【发布时间】:2016-12-30 20:02:57
【问题描述】:
我正在使用触发器来更新包含销售事实的表的更改日志表。当有人试图对表进行更新时,他们必须编写描述,然后记录更新(用户、时间、表、字段、Table_Unique_ID、旧值、新值)
我正在尝试对局部变量 @fieldname 使用 UPDATE() 触发函数。目标是这样我只比较更新的列的删除/插入值,而不是循环检查每一列。当我明确声明列名时,我已经能够使用 UPDATE() 函数,但如果我将变量设置为要检查的列名,则不能。
非常感谢有关如何优化此过程的任何建议!我还有很多东西要学,这是我第一次尝试记录更改。
下面是我的完整触发器:
ALTER TRIGGER [dbo].[TR_UpdateLog]
ON [dbo].[Test_Update_Trigger]
AFTER Update
AS
Declare @description nvarchar(1000)
, @UserName nvarchar(128)
, @oldValue nvarchar(255)
, @newValue nvarchar(255)
, @UniqueID nvarchar(255)
, @fieldname nvarchar(128)
, @oname NVARCHAR(100)
, @OldSQL nvarchar(max)
, @NewSQL nvarchar(max)
, @i int
, @c int
, @numcolumns int
, @numrows int;
DECLARE @updated_table TABLE (
idx int Primary Key identity(1,1)
, uniqueID nvarchar(255) NULL )
;
--Require the User to submit a description for the update
Set @description = (SELECT * FROM [dbo].[Fact_Bookings_Audit_Description])
TRUNCATE TABLE [dbo].[Fact_Bookings_Audit_Description]
IF @description is null
BEGIN
PRINT 'You must provide a description. Use the following text:
TRUNCATE TABLE [dbo].[Fact_Bookings_Audit_Description]
INSERT INTO [dbo].[Fact_Bookings_Audit_Description]
SELECT "Your Text Here--use Single Quotes"
Copy and paste above your query, type your description, and run the update again.
';
ROLLBACK TRANSACTION;
END
--Set User and Table name
Set @Username = system_User
SET @oname = (SELECT OBJECT_NAME(parent_id) from sys.triggers where object_ID = @@PROCID)
-------------------------------------------------------------
---create tables of updated items to reference for old/new values
INSERT INTO @updated_table
SELECT distinct Table_ID from DELETED
SELECT * INTO dbo.tempDelete FROM DEleted
SELECT * INTO dbo.tempInsert FROM inserted
--------------------------------------------------
--Set variables for loop through updated items
Set @i = 1
Set @numrows = (SELECT count(*) from @updated_table)
------------------------------------------------------------
---Set number of columns for loop through each field
Set @numcolumns = (SELECT MAx(ordinal_position) FROM information_schema.columns where table_name = @oname )
---------------------------------------------------------------
--If there was an update
IF @numrows > 0
BEGIN
--loop through each individual updated row
WHILE (@i <= (select max(idx) from @updated_table))
BEGIN
--reset the column variable
Set @c = 1
--loop through each column
WHILE (@c <= @numcolumns)
BEGIN
Set @fieldname = (SELECT Column_name FROM information_schema.columns
Where table_name = @oname AND ORDINAL_POSITION = @c)
/**This is what I want to use--
I would only like to do the comparison on columns which were updated, not cycle through every column**/
--IF UPDATE(@fieldname)
--BEGIN
--set values for old and new values as well as unique ID for log table
Set @UniqueID = (SELECT uniqueID from @updated_table u WHERE idx = @i)
Set @OldSQL = 'SELECT @oldvalue = ' + @fieldname + ' from dbo.tempdelete d WHERE d.Table_ID = ' + @UniqueID;
Set @NewSQL = 'SELECT @newvalue = ' + @fieldname + ' from dbo.tempInsert i WHERE i.Table_ID = ' + @UniqueID;
EXEC sp_executesql @oldSQL, N'@oldvalue nvarchar(128) output', @oldValue = @oldValue output
EXEC sp_executesql @newSQL, N'@newvalue nvarchar(128) output', @newValue = @newValue output
;
--Insert into log table if value is changed
IF isnull(@oldvalue,0) <> isnull(@newvalue,0)
BEGIN
INSERT INTO dbo.Fact_Bookings_ChangeAudit (Change_Date, Change_Time, [User], Table_Name, Field, Table_ID, Oldvalue, Newvalue, [Description])
VALUES(cast(datediff(DAY,0,getdate())as datetime),cast(getdate() as datetime),@UserName, @oname, @fieldname, @UniqueID, @oldValue, @newValue, @description);
END
--END
--next column
Set @c = @c + 1
END
--next record
Set @i = @i + 1
END
END
DROP TABLE dbo.tempDelete
DROP table dbo.tempInsert
GO
【问题讨论】:
-
我觉得里面的很多东西都是个坏主意。您也不需要
mysql标签。我知道这是您的第一个问题,但可能要评论的太多了。 -
在我看来,这个问题跨越了两个 stackexchange 站点,这个站点和代码审查。不过,由于您正在寻找优化,您可能想在那里发帖。 codereview.stackexchange.com
-
谢谢@shawnt00。我已经删除了 Mysql 标签。现在还在学习。如果您有任何与跟踪更改有关的好文章,我将不胜感激!
-
谢谢@scsimon!我知道我可以做很多优化。这是一个迭代过程。你知道为什么我不能在 UPDATE() 函数中使用局部变量吗?
-
update()中的变量没有意义。它会告诉您哪些列发生了更改以及您为何在触发器内。
标签: sql-server tsql database-trigger