我开始使用ADS sql表触发器来存储在一个特定表上完成的更改。这是一个想法:
//-------- sql trigger to store changes on patients table to auditLog Table
//----------------------------------------------------------------------
declare cChanges Char( 5000 );
declare allColumns Cursor ;
declare FieldName Char( 25 );
declare StrSql Char( 255 );
declare @new cursor as select * from __new;
declare @old cursor as select * from __old;
open @old;
fetch @old;
open @new;
fetch @new;
Set cChanges = '';
Open AllColumns as Select * from system.columns where parent = 'patients';
while fetch allColumns DO
// Try
FieldName = allColumns.Name;
StrSql = 'IF @new.'+FieldName
+ '<> @old.'+FieldName
+' and @old.'+FieldName + '<> [ ] THEN '
+ 'cChanges = Trim( '+cChanges+' ) + @old.'+FieldName
+ ' Changed to ' + '@new.'+fieldname
+ ' | '+ 'ENDIF ; ' ;
Execute Immediate StrSql ;
// Catch ALL
// End Try;
End While;
if cChanges <> '' THEN
Insert Into AuditLog ( TableKey, Patient, [table], [user], creation, Changes )
values( @new.patient, @new.patient, [Patietns], User(), Now(), cChanges ) ;
ENDIF;
CLOSE AllColumns;
//--------------------------
报告变量cChanges的上述触发器代码错误不存在。
有人可以帮忙吗?
雷纳尔多。
答案 0 :(得分:1)
我认为问题与动态SQl有关,试图设置触发器体中声明的值。
e.g。您的cChanges = TRIM(
语句可能导致问题,因为cChanges不存在该上下文。
您应该使用绑定变量来完成此操作,而不是尝试使用=符号进行设置。
您可以在他们的文档中看到他们说您无法通过转到
直接访问这些变量答案 1 :(得分:1)
问题确实是您无法立即访问脚本中的本地变量。你能解决的问题是使用临时表:
//-------- sql trigger to store changes on patients table to auditLog Table
//----------------------------------------------------------------------
declare cChanges Char( 5000 );
declare allColumns Cursor ;
declare FieldName Char( 25 );
declare StrSql Char( 255 );
Set cChanges = '';
Open AllColumns as Select * from system.columns where parent = 'patients';
while fetch allColumns DO
// Try
FieldName = allColumns.Name;
StrSql = 'SELECT n.FieldName newVal,'
+ 'o.FieldName oldVal '
+ 'INTO #MyTrigTable '
+ 'FROM __new n, __old o';
EXECUTE IMMEDIATE strSQL;
IF ( SELECT oldVal FROM #myTrigTable ) <> '' THEN
IF ( SELECT newVal FROM #myTrigTable ) <> ( SELECT oldVal FROM #myTrigTable ) THEN
cChanges = 'Construct_SomeThing_Using_#myTrigTable_or_a_cursorBasedOn#MyTrigTable';
INSERT INTO AuditLog ( TableKey, Patient, [table], [user], creation, Changes )
SELECT patient, patient, 'Patietns', User(), Now(), cChages FROM __new ;
END;
END;
DROP TABLE #myTrigTable;
// Catch ALL
// End Try;
End While;
CLOSE AllColumns;
//--------------------------