TERADATA SQL,我将SQL语句存储在表中。我想用另一个表填充那些SQL语句的结果。每个行和每列的SQL语句都不同。你能告诉我如何实现它吗?我试图通过存储过程和Shell脚本获得结果。但是,我无法正确编码。
答案 0 :(得分:0)
这是一个很好的准系统程序,用于拉出这样的东西。它变得有点毛茸茸,因为:
我怀疑你在设置这个问题时会遇到各种各样的错误,但我相信这非常接近于一个工作程序:
CREATE PROCEDURE <yourdatbase>.MyNewProcedure()
BEGIN
--Declare variables to hold the three fields as we loop through them with the cursor
--You'll need to change these types to match your table's data type so we can fetch
-- them without error inside the cursor loop
DECLARE customerID INT;
DECLARE customerName VARCHAR(50);
DECLARE sqlQUERY as VARCHAR(10000);
DECLARE source_table_cursor CURSOR FOR SELECT customerID, customerName, SQLQuery FROM <yourdatabase>.yoursourcetable FOR READ ONLY;
OPEN source_table_cursor;
looplabel:
LOOP
--We'll need a cursor for a dynamic statement
--And we'll also need an integer to catch your query
--results (Assuming they are all like (Sum(<somefield>) or some
--type of INT
DECLARE C1 CURSOR FOR S1;
DECLARE sqlResults as INT;
FETCH source_table_cursor INTO customerID, customerName, sqlQuery;
--WOAH THERE! Cursor issues something went wrong die die die
IF (SQLSTATE ='02000') THEN
LEAVE label1;
END IF;
--Now that we have a record and a sql statement we will need another cursor
--where we will execute, dynamically, the SQL statement and then fetch the
--single record result to update our target table
PREPARE S1 FROM sqlQuery;
OPEN C1;
FETCH C1 INTO sqlResults;
--Now we can INsert into your target table
INSERT INTO <yourdatabase>.yourtargettable (customerID, customerName SQL_RESULT)
VALUES (customerID, customerName, sqlResults);
CLOSE C1;
END LOOP looplabel;
CLOSE demographic_cursor;
END