sqlsnowflake-cloud-data-platformdata-conversioncode-conversion

Trying to convert reassigning declared variables SQL code to Snowflake


I’m trying to convert the following SQL code to snowflake using the snowflake UI. The converted snowflake code will be used in a stored procedure.

DECLARE @NumofDays int
SET @NumofDays = 15

Declare @loaddt smalldatetime

If @NumofDays = 1
BEGIN set @loaddt = getdate() end
Else
Begin set @loaddt = ‘1900-01-01’ end

Insert into ##temptable
Select @loaddt as Loaddt

This is what I have tried in Snowflake and it does not insert the :loaddt into the temp table, giving me the error “INVALID IDENTIFIER ‘LOADDT’ “:

BEGIN
    LET NUMofDays int := 1;
    
    BEGIN
        CASE WHEN NUMofDays = 1 THEN LET loaddt datetime := current_date();
        ELSE LET loaddt datetime := '1900-01-01'
        END;
    END;
    
    INSERT INTO (schemaname).TEMPTABLE
        SELECT :loaddt as Loaddt;
END;

(EDITED) I thought I had figured it out when I declared load date after NumofDays as in the following code but realized that while it did allow my code to run, it was not inserting the correct date if I changed numofdays to a different number.

CREATE OR REPLACE LOCAL TEMPORARY TABLE (schemaname).TEMP AS
    SELECT to_timestamp_ntz(current_date) as loaddate;

BEGIN
    LET NUMofDays int := 1;
    LET loaddt datetime := to_date('2023-02-10');
    
    BEGIN
        CASE WHEN NUMofDays = 1 THEN 
            LET loaddt datetime := current_date();
        ELSE 
            LET loaddt datetime := to_date('1900-01-01');
        END;
    END;
    
    INSERT INTO (schemaname).TEMP
        SELECT :loaddt as loaddate;
END;

I’d really appreciate any advice on how to approach this conversion bcuz I have been racking my brain for a few days now and can’t get the code to run properly. Im also new to snowflake, so im sure im missing something important that I couldn’t find in the documentation.


Solution

  • I think the main problem is that you're declaring the variable again inside your CASE block instead of just assigning a value to it. Take out those extra LET keywords.

    CASE WHEN NUMofDays = 1 THEN
        loaddt := current_date();
    ELSE
        loaddt := to_date('1900-01-01');
    END;
    

    For more information, check out Understanding Blocks in Snowflake Scripting and Working with Variables.