Reputation: 4400
I am trying to define a stored procedure in Snowflake as follows. But it is erroring out on the variable binding for :table_name
.
Error: `Syntax error: unexpected ‘into’
How do I achieve this?
CREATE OR REPLACE PROCEDURE SP__INSERT_TO_CUSTOMERS(table_name varchar)
RETURNS string
LANGUAGE SQL
AS
BEGIN
insert into :table_name (customer_name)
select distinct
customer_name
from orders;
RETURN ‘SUCCESS’;
END;
Upvotes: 0
Views: 36
Reputation: 46
In Snowflake, when using dynamic table names in stored procedures, you need to use the EXECUTE IMMEDIATE statement since table names can't be parameterized directly using bind variables. Here's the corrected version:
CREATE OR REPLACE PROCEDURE SP__INSERT_TO_CUSTOMERS(table_name varchar)
RETURNS string
LANGUAGE SQL
AS
$$
BEGIN
EXECUTE IMMEDIATE 'INSERT INTO ' || :table_name || ' (customer_name)
SELECT DISTINCT customer_name
FROM orders';
RETURN 'SUCCESS';
END;
$$;
Key changes made:
You can then call the procedure like this:
CALL SP__INSERT_TO_CUSTOMERS('your_table_name');
Upvotes: 0
Reputation: 4400
Looks like for table names we have to use the IDENTIFIER()
keyword as follows:
CREATE OR REPLACE PROCEDURE SP__INSERT_TO_CUSTOMERS(table_name varchar)
RETURNS string
LANGUAGE SQL
AS
BEGIN
insert into IDENTIFIER(:table_name) (customer_name)
select distinct
customer_name
from orders;
RETURN ‘SUCCESS’;
END;
Upvotes: 0
Reputation: 2830
Like @Barmar mentioned in comment, you can define a variable where you can prepare your sql statement and then execute it using EXECUTE IMMEDIATE
.
Example procedure which I tested by creating a sample order
and customer
table
CREATE OR REPLACE PROCEDURE SP__INSERT_TO_CUSTOMERS(table_name VARCHAR)
RETURNS STRING
LANGUAGE SQL
AS
$$
BEGIN
LET sql_insert STRING;
sql_insert := 'INSERT INTO ' || table_name || ' (customer_name)
SELECT DISTINCT customer_name FROM orders;';
EXECUTE IMMEDIATE sql_insert;
RETURN 'SUCCESS';
END;
$$;
Call the procedure
Check whether data is inserted in Customers
Upvotes: 0