I'm facing an error while passing date records into variable .
Want to convert the records into date format 'YYYY-MM-DD' instead of 'Feb 20 2022 HH:MM:SS' format.
Do we have any date conversion methods in javascript ?.
CREATE OR REPLACE PROCEDURE sp_ADDWORKDAYS_CUTOFF_PP(SRC_DB STRING, SRC_SCHEMA STRING)
RETURNS varchar
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS
$$
var D_STARTDATE = '';
var D_WORKDAYS = '';
var seq_query = `SELECT "DELIV_CR_DT" AS D_STARTDATE,DERIVED_COL AS D_WORKDAYS FROM `+SRC_DB+`.`+SRC_SCHEMA+`.v_v_testing`;
var seq_stmt = snowflake.createStatement({ sqlText: seq_query});
var seq_result = seq_stmt.execute();
while (seq_result.next()){
var STARTDATE = seq_result.getColumnValue(1);
var WORKDAYS = seq_result.getColumnValue(2);
var sub_call_query = `CALL `+SRC_DB+`.`+SRC_SCHEMA+`.sp_OTD_ADDWORKDAYS(`+STARTDATE+`,`+WORKDAYS+`,'01')`;
var sub_call_stmt = snowflake.createStatement({ sqlText: sub_call_query ,binds: [STARTDATE.toISOString(),WORKDAYS] });
var sub_call_result = sub_call_stmt.execute();
sub_call_stmt.next();
var return_value = sub_call_result.getColumnValue(1);
}
$$
;
error:
SQL compilation error:
syntax error line 1 at position 52 unexpected 'Feb'.
At Statement.execute, line 14 position 40 (line 36)
You can try to include something like this in your logic for date conversion -
Using Java-script procedure -
CREATE OR REPLACE PROCEDURE "GETJOBS"(SRC_DB STRING, SRC_SCHEMA STRING)
RETURNS varchar
LANGUAGE JAVASCRIPT
EXECUTE AS caller
AS
$$
var D_STARTDATE = '';
var D_WORKDAYS = '';
var seq_query = `SELECT to_char(to_timestamp('Feb 20 2022 10:10:10','Mon DD YYYY HH24:MI:SS'), 'YYYY-MM-DD') AS D_STARTDATE`;
var seq_stmt = snowflake.createStatement({ sqlText: seq_query});
var seq_result = seq_stmt.execute();
seq_result.next();
return seq_result.getColumnValue(1);
$$
;
Procedure call -
call getjobs('a','b');
GETJOBS
2022-02-20
Using UDF -
create or replace function fn_getjobs(dt string)
returns string as
$$
select to_char(to_timestamp(dt,'Mon DD YYYY HH24:MI:SS'), 'YYYY-MM-DD') as return_dt
$$
;
Function call
select fn_getjobs('Feb 20 2022 10:10:10') as dt;
DT
2022-02-20
Related
I have ran in to an issue when calling 2 stored procedures within another stored procedure in Snowflake. The below is my requirement
if ((to_number((to_char(CURRENT_DATE,'dd')))=10)) then we need to call sp name edw.bison_details
And everyday if the above condition is satisfied or not, eds.bison_delta_details stored procedure needs to run with the main stored procedure.
Can anybody help me with that?
Updated...
I have wrote a calling code in snowflake. but its giving an error like,
SQL compilation error: syntax error line 1 at position 0 unexpected 'if'.
This is the code that leads to the error message when calling a sp within another sp in snowflake.
if ((to_number((to_char(CURRENT_DATE,'dd')))==5))
CALL STG.BISON_LAND_DATA('`+ID+`'::VARCHAR,CURRENT_TIMESTAMP()::TIMESTAMP_NTZ::VARCHAR,
'{"name": "`+name+`","task_name": "`+task_name+`","sp": "STG.BISON_LAND_DATA","up_date": "`+upd_date+`","date": "`+date+`","id": "`+ID+`"}'::VARCHAR)
How to fix this issue?
to_char(CURRENT_DATE,'dd') gives you day of month but simpler would be to use DAYOFMONTH thus the first line can become:
if( DAYOFMONTH(CURRENT_DATE) == 5 ) {
...
}
and your StoredProc call can be pulled apart to see what makes sense and doesn't like:
var parm1 = '`+ID+`'::VARCHAR;
var parm2 = CURRENT_TIMESTAMP()::TIMESTAMP_NTZ::VARCHAR;
var json_str = '{"name": "`+name+`","task_name": "`+task_name+`","sp": "STG.BISON_LAND_DATA","up_date": "`+upd_date+`","date": "`+date+`","id": "`+ID+`"}'::VARCHAR;
CALL STG.BISON_LAND_DATA(parm1, parm2, json_str);
in the context of the code shown, it doesn't make sense to use all three quote styles, given we are starting the strings with ' quotes, to break them to do string concatenation you could just use a normal single quote again.
var json_str = '{"name": "'+ name +'","task_name": "'+ task_name +'","sp": "STG.BISON_LAND_DATA","up_date": "'+ upd_date +'","date": "'+ date +'","id": "'+ ID +'"}'::VARCHAR;
parm1 is just an toString() thus could be
var parm1 = ID.toString();
json_str is a string representing json object, given you are in JavaScript, you could just create the object, and then toString() that.. thus it all becomes:
if( DAYOFMONTH( CURRENT_DATE ) == 5 ) {
var parm1 = ID.toString();
var parm2 = CURRENT_TIMESTAMP()::TIMESTAMP_NTZ::VARCHAR;
var json_obj = {name: name, task_name: task_name, sp: "STG.BISON_LAND_DATA", up_date: upd_date, date: date, id: ID };
CALL STG.BISON_LAND_DATA(parm1, parm2, json_obj.toString());
}
And given your question about then actually code that you are correct, and copying the logic from the linked question on Execute stored procedure inside another stored procedure in snowflake and doc's on working with Stored Procedures together:
it should become:
if( DAYOFMONTH( CURRENT_DATE ) == 5 ) {
var parm1 = ID.toString();
var parm2 = CURRENT_TIMESTAMP()::TIMESTAMP_NTZ::VARCHAR;
var json_obj = {name: name, task_name: task_name, sp: "STG.BISON_LAND_DATA", up_date: upd_date, date: date, id: ID };
var cmd = "CALL STG.BISON_LAND_DATA(:1, :2, :3)";
var stmt = snowflake.createStatement(
{
sqlText: cmd,
binds: [parm1, parm2, json_obj.toString()]
}
);
var result1 = stmt.execute();
result1 .next();
var val = result1.doSomeThingWithResults...
}
Basically I have created the notification alert using integrating AWS and Snowflake.
I want to add variable to my select statement. But its not working. So it will be for example "The token of user has expierd (name of the user).
Here is my function
`create or replace external function helloemailworld
(Sender varchar,Receiver Varchar , SUBJECT varchar, BODY_TEXT varchar)
returns variant
api_integration = hellotesting
as 'https://....execute-api.eu-...l-1.amazonaws.com/dev/helloworld';`
and here is my procedure
create or replace procedure Notification()
returns variant
language javascript
EXECUTE AS caller
as
$$
var my_sql_command = "select * from notification";
var statement1 = snowflake.createStatement( {sqlText: my_sql_command} );
var result_set1 = statement1.execute();
while (result_set1.next()) {
var column1 = result_set1.getColumnValue(1);
var column2 = result_set1.getColumnValue(2);
var column3 = result_set1.getColumnValue(3);
var execute = "select helloemailworld('lukasz#gmail.com','lukasz#op.pl','Alert', 'The token of user has expierd' + column1);"
var statement2= snowflake.createStatement( {sqlText: execute} );
var result_set2 = statement2.execute();
}
$$
;
The column 1 is a variable and in notification table first column is also a variable
Looking for advice on how to correct these two stored procedures so that one will trigger the other.
Stored procedure 2 is designed to simply create Table 2:
CREATE OR REPLACE PROCEDURE create_table_2()
returns string not null
language javascript
as
$$
var create_table_2 = `
create or replace table DATABASE.SCHEMA.TABLE_2
(
COL_1 string,
COL_2 string,
COL_3 date
)
;
`
var create_table_2_cmd = snowflake.createStatement({sqlText: create_table_2});
var result = sql_create_table_2.execute();
return 'Table 2 created';
$$;
And stored procedure 1, which should be run first, create table 1 and then run stored procedure 2:
CREATE OR REPLACE PROCEDURE create_table_1()
returns string not null
language javascript
as
$$
var create_table_1 = `
create or replace table DATABASE.SCHEMA.TABLE_1
(
COL_1 string,
COL_2 string,
COL_3 date
)
;
`
var create_table_1_cmd = snowflake.createStatement({sqlText: create_table_1 });
var result = create_table_1_cmd .execute();
return 'Table 1 created';
var call_next_function_cmd = `
call create_table_2();
;
`
var call_next_func = snowflake.createStatement({sqlText: call_next_function_cmd});
var final = call_next_func.execute();
$$;
The SQL code within the create_table_1() procedure executes without issue but does not call the create_table_2() procedure. Is there an adjustment to be made that can trigger this?
The return has to be moved to the end of stored procedure, at current position it makes the second call unreachable code:
CREATE OR REPLACE PROCEDURE create_table_1()
returns string not null
language javascript
as
$$
var create_table_1 = `
create or replace table DATABASE.SCHEMA.TABLE_1
(
COL_1 string,
COL_2 string,
COL_3 date
)
;
`
var create_table_1_cmd = snowflake.createStatement({sqlText: create_table_1 });
var result = create_table_1_cmd .execute();
//return 'Table 1 created'; -- << HERE
var call_next_function_cmd = `
call create_table_2();
;
`
var call_next_func = snowflake.createStatement({sqlText: call_next_function_cmd});
var final = call_next_func.execute();
return '...';
$$;
I can retrieve the values of before(0) and after counts(4) from the below statements, but when I make use of those variables (load_cnt_before, load_cnt_after) from the code below and refer them to have the values inserted into a table it says it cant find the variables(refer to error below). How can I use those values to INSERT them into table.
Error: Execution error in stored procedure REC_COUNT_CHECK: SQL compilation error: error line 1 at position 114 invalid identifier 'LOAD_CNT_BEFORE' At Statement.execute, line 25 position 90
Code:
CREATE OR REPLACE PROCEDURE REC_COUNT_CHECK()
RETURNS VARCHAR LANGUAGE JAVASCRIPT
AS $$
/***** Get the Record Count before Refresh ****/
var load_cnt=`SELECT Count(*) as record_cnt from "PLNG_ANALYSIS"."LOADDATA"."LOAD_VERIFICATION" WHERE EXTRACTDATE=Current_date()-1 ;`
var load_cnt_check = snowflake.createStatement({sqlText: load_cnt}).execute();
load_cnt_check.next();
load_cnt_before = load_cnt_check.getColumnValue(1);
/***** Execute the SP ****/
var sp_call = "CALL LOAD_VERIFICATION()"; /***Refreshes data in table LOAD_VERIFICATION***/
var result = snowflake.execute({sqlText: sp_call});
result.next();
var return_msg2 = result.getColumnValue(1);
/***** Check the After Refresh Count ****/
var load_cnt_after=`SELECT Count(*) as record_cnt from "PLNG_ANALYSIS"."HFM"."LOAD_VERIFICATION" WHERE EXTRACTDATE=Current_date() ;`
var load_cnt_check_after = snowflake.createStatement({sqlText: load_cnt_after}).execute();
load_cnt_check_after.next();
load_cnt_after= load_cnt_check_after.getColumnValue(1);
/***** INSERT BEFORE AND AFTER COUNTS INTO LOG TABLE ****/
var insert_status_sp1=`INSERT INTO LOAD_STATUS_LOG_KK values (Current_TIMESTAMP(),1,'LOAD_VERIFICATION','Success','',**load_cnt_before,load_cnt_after**,1);`
var exec_sp1_status = snowflake.createStatement({sqlText: insert_status_sp1}).execute();
exec_sp1_status.next();
return 'Success'
$$;
CALL REC_COUNT_CHECK();
JS variables should be passed into SQL query. The mechanism is called Binding Variables
var insert_status_sp1=`INSERT INTO LOAD_STATUS_LOG_KK values (Current_TIMESTAMP(),1,'LOAD_VERIFICATION','Success','',:1,:2,1);`
var exec_sp1_status = snowflake.createStatement(
{sqlText: insert_status_sp1,binds:[load_cnt_before,load_cnt_after]}
).execute();
var P_ENV = 'int'
var p_sqlText: CALL LS_**${P_ENV}**.HIID_SECURED.sp_getStatCertSaltValue(:1,:2);
var stmt = snowflake.createStatement({sqlText:p_sqlText,binds: [P_ENV,P_STARTCERTID] });
var rs = stmt.execute();
rs.next();
var p_saltvalue= rs.getColumnValue(1);
Unable to execute these lines in an stored procedure - calling the stored procedure with in the stored procedure - Thoughts please
Can you share the error message you get?
When I tried to test it, I was able to call the procedure:
create or replace procedure int_sp_getStatCertSaltValue( v1 varchar, v2 varchar)
returns object
language javascript
as
$$
return { "v1": V1, "v2": V2 };
$$;
create or replace procedure spinsp()
returns object
language javascript
as
$$
var P_ENV = 'int';
var P_STARTCERTID = 1
var p_sqlText = `CALL ${P_ENV}_sp_getStatCertSaltValue(:1,:2)`;
var stmt = snowflake.createStatement({sqlText:p_sqlText,binds: [P_ENV,P_STARTCERTID] });
var res = stmt.execute();
res.next();
return res.getColumnValue(1);
$$
;
call spinsp();
+----------------------------+
| SPINSP |
+----------------------------+
| { "v1": "int", "v2": "1" } |
+----------------------------+