简体   繁体   中英

Insert Into table Teradata dynamic stored procedure SQL

I am trying to create a Stored Procedure in Teradata that will accept various arguments. My query has 4 passes of SQL where it creates 3 lots of volatile tables. Within the Select statements is the SQL that I need to be dynamic and this is where I run into problems.

Here is my SQL:

CREATE PROCEDURE "mydb"."test_sp20" (DepID integer) --DepID is my parameter
DYNAMIC RESULT SETS 1 SQL SECURITY OWNER
BEGIN

DECLARE q1 VARCHAR(10000);
DECLARE cur1 CURSOR WITH RETURN ONLY TO client FOR s1;

CREATE VOLATILE TABLE mydb.tbl_1 , no fallback, no log(
Consumer_Unit_Id    INTEGER, 
Price_Promotion_Id  INTEGER, 
Promotion_Id    INTEGER)
primary index (Consumer_Unit_Id, Price_Promotion_Id, Promotion_Id) on commit preserve rows ;

INSERT INTO mydb.tbl_1
SELECT * FROM mydb.tbl_1
SET q1 = 'Select * from mydb.tbl_1'
PREPARE s1 FROM q1;
OPEN cur1;
END;

This works fine as a SP with static SQL but I need the Select statements to be dynamic in that within them I have Department and Sections parameters that I want to be able to pass accross. eg

INSERT INTO mydb.tbl_1
SQL = 'Select * from mydb.tbl_1 where Department_ID = ' || DepID ||'

I've also tried:

SQL = 'INSERT INTO Select * from mydb.tbl_1 where Department_ID = ' || DepID ||'

In both cases I get the following error:

7683:  TEST_SP20:Invalid statement specified inside a dynamic declare cursor/SQL statement

I seem to be able to have a dynamic SQL string but I can't have a INSERT INTO SELECT string??

@dnoeth helped me get this started so any more help is much appreciated.

You didn't tell that you want to INSERT/SELECT using Dynamic SQL, a cursor is only needed when you want to return a result set from your SP.

DECLARE q1 VARCHAR(10000);

SET q1 = 'INSERT INTO Select * from mydb.tbl_1 where Department_ID = ' || TRIM(DepID) ||';';

EXECUTE IMMEDIATE q1;

But if only the values passed to the WHERE-condition are supposed to be dynamic you might better apply a prepared statement (which could be used multiple times):

SET q1 = 'INSERT INTO Select * from mydb.tbl_1 where Department_ID = ?;';

PREPARE stmt FROM q1;

EXECUTE stmt USING DepID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM