How to execute dynamic SQL in Teradata

筅森魡賤 提交于 2019-12-17 21:33:19

问题


Is there any way to submit dynamically generated SQL to Teradata? I've written a query that will create the code to denormalize a table. Right now, I am pulling the code down to my client (SAS) and resubmitting it in a second step. I am not familiar with either Teradata macros or procedures; would something like that work?

To illustrate, I have a table defined like this:

create multiset table MYTABLE
    (  RECID  integer generated always as identity
              ( start with 1
               increment by 1
               minvalue -2147483647
               maxvalue 2147483647
               no cycle )
     , SNAP_DATE  date format 'YYYY/MM/DD'
     , EMAIL_DATE date format 'YYYY/MM/DD'
     , FREQ integer
    )
unique primary index ( RECID  )

The table is populated every day (SNAP_DATE) and is used to monitor changes to an email_date in another table. The following query returns the code that I can run to create my denormalized view:

select RUN_THIS
from (
    select RUN_THIS, RN
    from (
        select 'select EMAIL_DATE ' (varchar(100)) as RUN_THIS
              , 0 (int) as RN
          ) x

    union all
    select ', sum( case when SNAP_DATE = date '''
             || (SNAP_DATE (format 'yyyy-mm-dd') (char(10)) )
             || ''' then FREQ else 0 end ) as D'
             || (SNAP_DATE (format 'yyyymmdd') (char(8)) ) as RUN_THIS
          , row_number() over ( partition by 1 order by SNAP_DATE ) as RN
    from ( select distinct SNAP_DATE 
           from MYTABLE 
           where SNAP_DATE > current_date - 30) t1

    union all
    select RUN_THIS, RN
    from (
        select 'from MYTABLE group by 1 order by 1;' as RUN_THIS
                , 10000 as RN
          ) y
    ) t
order by RN

I export the result of the above query to a file on my client, then turn around and submit that file back to Teradata. I'm hoping there is some way to store this complete definition in some Teradata object so it can be executed directly.


回答1:


You may find success putting this in a stored procedure using the DBC.SysExecSQL command.

Here is an overly simplified example of a stored procedure in Teradata. Obviously in production would want an error handler defined to address things like invalid database objects. Furthermore, you could return the SQLSTATE back as a parameter to test for whether the stored procedure completed successfully or not.

CREATE PROCEDURE SYSDBA.CommentDatabase
(
  IN P_Database VARCHAR(30),
  IN P_Comment VARCHAR(255), 
  OUT MSG
)
MAIN:  --Label
BEGIN

  DECLARE  P_SQL_TEXT     VARCHAR(4000);

  SET P_SQL_TEXT='COMMENT ON DATABASE '||P_DBNAME||' AS '''||P_COMMENT||'''';
  CALL dbc.SysExecSQL (:P_SQL_TEXT);

  SET MSG = 'Database '||P_DBNAME||' commented successfully!';
END;


来源:https://stackoverflow.com/questions/13895370/how-to-execute-dynamic-sql-in-teradata

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