2

我开始使用 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 的上述触发代码错误不存在。

有人可以帮忙吗?

雷纳尔多。

4

2 回答 2

1

我相信问题与您尝试设置触发器主体中声明的值的动态 SQl 有关。

例如,您的cChanges = TRIM(陈述可能会导致问题,因为 cChanges 不存在该上下文。

您应该使用绑定变量来完成此操作,而不是尝试使用 = 符号进行设置。

您可以在他们的文档中看到他们说您无法直接访问这些变量

http://devzone.advantagedatabase.com/dz/webhelp/advantage9.1/advantage_sql/sql_psm_ script /execute_immediate.htm

于 2011-04-02T00:04:13.553 回答
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;
//--------------------------
于 2011-04-08T21:38:48.090 回答