How to use variables in Teradata SQL Macros

我的未来我决定 提交于 2019-12-10 11:54:13

问题


I'm wanting to use variables inside my macro SQL on Teradata.

I thought I could do something like the following:

REPLACE MACRO DbName.MyMacro  
(  
   MacroNm   VARCHAR(50)  
)  
AS  
(  

   /* Variable to store last time the macro was run */  

   DECLARE V_LAST_RUN_DATE TIMESTAMP;  


   /* Get last run date and store in V_LAST_RUN_DATE */  

   SELECT LastDate  
   INTO V_LAST_RUN_DATE  
   FROM DbName.RunLog  
   WHERE MacroNm = :MacroNm;  


   /* Update the last run date to now and save the old date in history */  

   EXECUTE MACRO DbName.RunLogUpdater(  
      :MacroNm  
     ,V_LAST_RUN_DATE  
     ,CURRENT_TIMESTAMP  
   );  

);  

However, that didn't work, so I thought of this instead:

REPLACE MACRO DbName.MyMacro  
(  
   MacroNm   VARCHAR(50)  
)  
AS  
(  

   /* Variable to store last time the macro was run */  

   CREATE VOLATILE TABLE MacroVars AS  
   (  
         SELECT  LastDate AS V_LAST_RUN_DATE  
           FROM  DbName.RunLog  
          WHERE  MacroNm = :MacroNm;  
   )  
   WITH DATA ON COMMIT PRESERVE ROWS;  


   /* Update the last run date to now and save the old date in history */  

   EXECUTE MACRO DbName.RunLogUpdater(  
      :MacroNm  
     ,SELECT V_LAST_RUN_DATE FROM MacroVars  
     ,CURRENT_TIMESTAMP  
   );  

);  

I can do what I'm looking for with a Stored Procedure, however I want to avoid for performance.

Do you have any ideas about this?
Is there anything else I can try?

Cheers
Tim


回答1:


You can't DECLARE a variable inside of a macro. What you are trying to accomplish could be handled with an UPDATE statement if you so choose.

UPDATE TGT
FROM <dbname>.<target table> TGT
   , (SELECT MacroName
           , LastRunDate
      FROM <dname>.<source table>
     ) SRC
SET LastRunDate = SRC.LastRunDate
  , EffectiveTimestamp = CURRENT_TIMESTAMP(0)
WHERE TGT.MacroName = SRC.MacroName
;


来源:https://stackoverflow.com/questions/2687819/how-to-use-variables-in-teradata-sql-macros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!