i am inserting a query from a variable into log table , but it is throwing error as below.
Failed: Code: 100183\n State: P0000\n Message: SQL compilation error:
syntax error line 3 at position 33 unexpected 'MM'.
syntax error line 7 at position 58 unexpected 'Current_Timestamp'
please refer INSERT_VOL2 where we are iserting values into a log table by using parameters. where v_WORK_SQL_ALRT_VOL2 is having the query , same query we are trying to insert into a log table. but it is throwing error.
below is the procedure code.
CREATE OR REPLACE PROCEDURE CDW_PROC.SAMPLE_PROCEDURE(col1 FLOAT, COL2 VARCHAR, COL3 VARCHAR, COL4 VARCHAR, COL5 VARCHAR, COL6 VARCHAR)
RETURNS VARCHAR(10000)
LANGUAGE JAVASCRIPT
STRICT
EXECUTE AS OWNER
AS
$$
try
{
var v_FILTER_ID=0;
var v_A_TYPE=COL2
var v_TYPE=COL3
var v_FILTER_ATTRIBUTE
var v_ORG=COL4;
var v_FILTER_CONDITION,v_FILTER_VALUE,v_FILTER_DESC;
var v_BRAND ='v_BRAND';
var v_F_TIME_CUR = 'v_F_TIME_CUR';
var v_F_TIME_PREV='v_F_TIME_PREV';
var v_F_RANK='v_F_RANK';
var v_F_TIME_BUCKET='v_F_TIME_BUCKET';
var v_CODE='v_CODE';
var v_ID=col1;
var v_TIME_FRAME=COL5;
var v_WK_MTH_FLG=COL6;
var SEL_SQL=snowflake.execute({sqlText: "SELECT ID,TYPE,ORG,SUB_TYPE,FILTER_ID,FILTER_DESC,FILTER_ATTRIBUTE,FILTER_CONDITION,FILTER_VALUE,TIME_FRAME,WK_MTH_FLG FROM CDW_DB.FCT_TABLE WHERE ID=? AND TYPE =? AND SUB_TYPE =? AND ORG=? AND TIME_FRAME=? AND WK_MTH_FLG =?",binds:[v_ID,v_A_TYPE, v_TYPE, v_ORG, v_TIME_FRAME, v_WK_MTH_FLG]});
while(SEL_SQL.next())
{
var v_ID=SEL_SQL.getColumnValue(1);
var v_A_TYPE=SEL_SQL.getColumnValue(2);
v_WORK_SQL_ALRT_VOL2 = `insert into CDW_US_DIMS_DB.PLANNED_CALL1
select DISTINCT FCT.PFZ_CUST_ID,
CAST(TO_CHAR(FCT.CALL_DATE_VOD ,'MM/DD/YYYY') AS VARCHAR(10)) AS PLANNED_CALL_DATE,
RANK() OVER (PARTITION BY FCT.PFZ_CUST_ID ORDER BY FCT.DT_SK ASC,FCT.CREATEDDATE ASC) AS RNK
from CDW_US_PROCESSING_VW.VVA_REP_PLANNED_CALLS FCT WHERE PFZ_CUST_ID <> -1
and FCT.${v_F_SALES_ORG_CODE}
and CALL_DATE_VOD > CURRENT_TIMESTAMP(0) QUALIFY RNK=1;`;
var v_WORK_SQL_EXEC=snowflake.createStatement({sqlText: v_WORK_SQL_ALRT_VOL2});
var VOL2_RESULT=v_WORK_SQL_EXEC.execute();
var INSERT_VOL2=snowflake.execute({sqlText: "INSERT INTO CDW_DB.log_tbl VALUES ("+v_ID+",'"+v_A_TYPE+"','"+v_WORK_SQL_ALRT_VOL2+"',Current_Timestamp)"});
var RESULT='Success';
return RESULT;
}
catch(err)
{
RESULT="Failed: Code: "+err.code+"\\n State: "+ err.state;
RESULT+="\\n Message: "+err.message;
RESULT+="\\n Stack Trace:\\n"+err.StackTraceTxt;
return RESULT;
}
$$
;
The pasted code has multiple errors that would prevent it from working, or even giving that specific error message:
A block needs to be closed before catch with a }.
The variable col1 should be COL1.
v_F_SALES_ORG_CODE is never defined, but used.
Once all that is fixed, everything works well until these lines:
var v_WORK_SQL_EXEC=snowflake.createStatement({sqlText: v_WORK_SQL_ALRT_VOL2});
var VOL2_RESULT=v_WORK_SQL_EXEC.execute();
But then we find this:
var INSERT_VOL2=snowflake.execute({sqlText: "INSERT INTO CDW_DB.log_tbl VALUES ("+v_ID+",'"+v_A_TYPE+"','"+v_WORK_SQL_ALRT_VOL2+"',Current_Timestamp)"});
The problem is that v_WORK_SQL_ALRT_VOL2 is a full sql query - and inserting a full SQL query string in the middle of an insert statement will simply not work.
This code needs a lot of cleaning and work, but at least we found where the two errors in the question are coming from.
i am able to insert that values now, after assigning current_timestamp values to a variable and that variable is using in Insert query. Thank you for your suggestions. grately appriciated.
Related
var run_id_query = `INSERT INTO STG.RUN_STATUS (RUNID,STATUS,STATUS_DESCRIPTION)
VALUES (TO_CHAR(CURRENT_DATE,'YYYYMMDD'),0,'RUN START')`;
var run_id_stmt = snowflake.createStatement({ sqlText: run_id_query});
var run_id = run_id_stmt.execute();
getting error SQL compilation error: syntax error line 3 at position 8 unexpected 'ID_DEV'.
insert is present in STG schema, i am trying to insert it from INT schema
Could you break it down e.g.:
run_id_query = $$INSERT INTO STG.RUN_STATUS (RUNID,STATUS,STATUS_DESCRIPTION) VALUES (TO_CHAR(CURRENT_DATE,'YYYYMMDD'),0,'RUN START')$$;
execute immediate $run_id_query
I set this up a while ago in something that is not really used. I was under the impression that it worked at the time, but I'm trying to test it now and am getting some errors.
Here is my snowflake code:
var rs = snowflake.createStatement( { sqlText: "select count(*) from toptal.stage_resellers" } ).execute();
rs.next();
var resellers = rs.getColumnValue(1);
I that that var resellers was going to define a variable that would have the number of rows in stage_resellers, but I'm not confident of that.
I decided to test it just by inserting the value into a logging table that I am using into an unused column for the time being.
Here is that code:
var stmt1 = snowflake.execute ( { sqlText:`insert into toptal.processing_executions values ('merge into dim_resellers', current_timestamp, 'processing', :resellers);`});
I'm getting this error:
Execution error in store procedure PROCESSING: SQL compilation error: error line 1 at position 110 Bind variable :resellers not set. At Snowflake.execute, line 47 position 24
I tried futzing around with setting the variable, to no avail.
I have a feeling that I am mixing up environments here, but I'm not sure what's going on.
To execute:
var stmt1 = snowflake.execute ( { sqlText:`insert into toptal.processing_executions values ('merge into dim_resellers', current_timestamp, 'processing', :resellers);`});
variables has to be provided as ? or :1. Code becomes:
var stmt1 = snowflake.execute({
sqlText: `insert into toptal.processing_executions
values ('merge into dim_resellers', current_timestamp,
'processing', ?)`
,binds: [resellers] } );
More at documentation: Binding Variables
create or replace procedure test_09172(c_custkey varchar(25)
,c_mktsegment varchar(25)
,cname varchar(25)) returns string not null language javascript execute as owner as $$
var sqlquery="";
var fltConvUomPK="";
var fltConvFactorPK="";
var ParentClass="";
var VMAJOR="";
var VMINOR="";
try {
var sql_command =`SELECT C_ADDRESS,C_NATIONKEY
from customers
WHERE c_custkey=C_CUSTKEY and c_name=CNAME and C_MKTSEGMENT=C_MKTSEGMENT`;
var rs=snowflake.createStatement( {sqlText: sql_command});
var result_set1 = rs.execute();
}
catch(err)
{
return err.message
}
return rs.getSqlText(); $$;
While executing "call test_09172('537289','FURNITURE','Customer#000537289');"
I am getting below error.
JavaScript execution error: Uncaught TypeError: Cannot read property
'getSqlText' of undefined in TEST_09172 at ' return rs.getSqlText();'
position 14 stackstrace: TEST_09172 line: 28
Please help me on this to fix
The error seems related to an undefined object, but your code worked without any errors when I tried to reproduce it.
I noticed that you do not bind your parameters to your SQL:
var sql_command =`SELECT C_ADDRESS,C_NATIONKEY
from customers
WHERE c_custkey=C_CUSTKEY and c_name=CNAME and C_MKTSEGMENT=C_MKTSEGMENT`;
SQL is not case-sensitive, so you just compare the columns with themselves (c_custkey=C_CUSTKEY and C_MKTSEGMENT=C_MKTSEGMENT). c_name=CNAME will probably produce an error.
To avoid confusion between the column and parameter names, I rewrote the query:
create or replace procedure test_09172(c_custkey_p varchar(25)
,c_mktsegment_p varchar(25)
,c_name_p varchar(25)) returns string not null language javascript execute as owner as $$
var sqlquery="";
var fltConvUomPK="";
var fltConvFactorPK="";
var ParentClass="";
var VMAJOR="";
var VMINOR="";
try {
var sql_command =`SELECT C_ADDRESS,C_NATIONKEY
from customers
WHERE c_custkey=? and c_name=? and C_MKTSEGMENT=?`;
var rs=snowflake.createStatement( {sqlText: sql_command , binds:[ C_CUSTKEY_P, C_NAME_P , C_MKTSEGMENT_P ] });
}
catch(err)
{
return err.message
}
return rs.getSqlText();
$$;
On my tests, it works as expected but I don't have your data so you should test it.
The method getSqlText is available for the Statement object not ResultSet, see here:
getSqlText()
This method returns the text of the prepared query in the Statement object.
I have to add a variable MaxDate in my SQL Stored Proc (shown below). The code gets errored out since MaxDate is not represented by its value. Any idea on how I can pass a variable in a stored proc?
create or replace procedure Load_Employee()
returns varchar not null
language javascript
EXECUTE AS CALLER
as
$$
//Variable Initialization
var IntegrationTable ='EMPLOYEE';
var TypeID=0;
var MaxDate=' ';
var cmd = "Select max(COMPLETED_DATE) from SCHEMA.TABLE where TARGET_TABLE_NAME= " + "'" + IntegrationTable + "'" ;
var sql = snowflake.createStatement({sqlText: cmd});
var result = sql.execute();
result.next();
MaxDate=result.getColumnValue(1);
var cmd=` Insert into PersonTable
select SHA1(concat(Person_id,'|','Person')) ,12345678,SHA1(concat('Payroll','|','Pay','|', Load_Date)) ,current_timestamp() , Tenant
from Schema.PERSONTABLE where Date_Added >= MaxDate
where TYPE='ABC' ;`;
$$
;
If your query to get MaxDate works right, then the value should be in the variable. The problem is it's not being replaced in the sql variable defining the insert statement.
Since you're using backticks to open and close the string, you can use a special JavaScript notation to replace the variable with its value, ${MaxDate}.
Your definition of the insert statement would look like this:
var cmd=` Insert into PersonTable
select SHA1(concat(Person_id,'|','Person')) ,12345678,SHA1(concat('Payroll','|','Pay','|', Load_Date)) ,current_timestamp() , Tenant
from Schema.PERSONTABLE where Date_Added >= ${MaxDate}
where TYPE='ABC' ;`;
If that doesn't work, try cutting the SP short with return MaxDate; to see what got assigned to that variable. Also it's very helpful to check the query history view to see what SQL actually ran inside a stored procedure.
Also, I think this is the same SP that was having an issue with a null return. You'll need to return a string value using something like return 'Success'; or something to avoid getting an error for the null return. That's because of the returns varchar not null in the definition.
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();