0

I am trying to write a table function in Snowflake which takes two parameters as p_table_schema and p_table name and based on that executes the sql and will return the tabular result set. However, it is not getting compiled and throwing an error

Compilation of SQL UDF failed: SQL compilation error: syntax error line 3 at position 4 unexpected 'query_string'

Code:

CREATE OR REPLACE FUNCTION DWH_PROD_LAB.REPORT.TF_LATEST_FILE_UPLOAD (
    p_table_schema VARCHAR,
    p_table_name VARCHAR
)
RETURNS TABLE (
    PATH VARCHAR,
    DATE_STRING VARCHAR,
    FILE_NAME VARCHAR,
    STATUS VARCHAR
)
AS 
$$
DECLARE
    query_string VARCHAR;
BEGIN
    query_string := 'SELECT
        src_filename AS PATH,
        src_partition_key AS DATE_STRING,
        CASE
            WHEN POSITION(''/'', src_filename) > 0 THEN
                SPLIT(src_filename, ''/'')[ARRAY_SIZE(SPLIT(src_filename, ''/''))-1]
            ELSE
                src_filename
        END AS file_name,
        CASE
            WHEN src_partition_key = TO_CHAR(CURRENT_DATE, ''YYYYMMDD'') THEN
                ''LATEST FILE IS UPLOADED IN SNOWFLAKE''
            ELSE
                ''LATEST FILE IS NOT UPLOADED IN SNOWFLAKE''
        END AS STATUS
    FROM ' || p_table_schema || '.' || p_table_name || '
    QUALIFY ROW_NUMBER() OVER (ORDER BY src_partition_key DESC) = 1';

    RETURN QUERY EXECUTE IMMEDIATE query_string;
END;
$$;
James Z
  • 12,209
  • 10
  • 24
  • 44
Rupesh
  • 5
  • 2
  • You might find this helpful: https://stackoverflow.com/questions/62403809/how-to-write-dynamic-queries-in-snowflake-user-defined-functions – Limonka Feb 20 '23 at 20:40

0 Answers0