用动态SQL编写存储过程

时间:2019-07-09 13:49:07

标签: amazon-redshift plpgsql dynamic-sql

我想编写一个存储过程,该过程采用一个text参数(table_name),并基于该表名执行查询:从中选择count(*)并将发现的值写入表中。

这是(SELECT COUNT(*) FROM VARTABLE_NAME)部分,我不知道如何在Amazon Redshift中实现

CREATE OR REPLACE  PROCEDURE SP_LOGGING (VARSTART INT, VARRUNID INT , VARPHASE VARCHAR, VARTABLE_NAME VARCHAR)
AS $$

BEGIN
            IF VARSTART = 1 THEN
                BEGIN
                UPDATE AUDIT.RUN_TEST
                SET TABLE_NAME = VARTABLE_NAME
                ,"no_of_records_at_start" = (SELECT COUNT(*) FROM VARTABLE_NAME)
                END;

            ELSEIF VARSTART = 0 THEN    
                BEGIN
                UPDATE AUDIT.RUN_TEST
                SET TABLE_NAME = VARTABLE_NAME
                ,"no_of_records_at_end" = (SELECT COUNT(*) FROM VARTABLE_NAME)
                END;
            END IF;
END;
$$ LANGUAGE PLPGSQL;

1 个答案:

答案 0 :(得分:2)

您需要使用EXECUTE来运行动态SQL。

CREATE PROCEDURE sp_logging (
      varstart      INT
    , varrunid      INT 
    , varphase      VARCHAR
    , vartable_name VARCHAR ) 
AS $$
BEGIN
    IF varstart = 1 THEN
        EXECUTE 'UPDATE audit.run_test
                    SET table_name = '||vartable_name||'
                      , start_rows = (SELECT COUNT(*) FROM '||vartable_name||' )';
    ELSEIF varstart = 0 THEN    
        EXECUTE 'UPDATE audit.run_test
                    SET table_name = '||vartable_name||'
                      , end_rows = (SELECT COUNT(*) FROM '||vartable_name||')';
    ELSE 
        RAISE ERROR 'Value of `varstart` must be 1 or 0. Received `%`.',varstart;
    END IF;
END;
$$ LANGUAGE PLPGSQL;