2011-04-01 66 views
2

我在ADS sql表觸發器上啓動以存儲對一個特定表執行的更改。這裏的想法是: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不存在。

有人可以幫忙嗎?

Reinaldo。

+0

未必是恰當的,但「值(@ new.patient,@ new.patient,[惡性血液病],用戶()... 「一個錯字(即[Patietns]? – 2011-04-01 23:19:33

回答

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; 
//--------------------------