2017-08-28 157 views
1

TERADATA SQL,我将SQL语句存储在一个表中。我想用这些SQL语句的结果填充另一个表。每条行和每列的SQL语句都不相同。你能告诉我如何实现它吗?我试图通过存储过程和Shell脚本获得结果。但是,我无法正确编码。TERADATA SQL:通过存储在另一个表中的查询结果填充一个表

+0

你的SELECT语句或在INSERT语句中的表? – Andrew

+0

你有SQL语句存储在一个表中。在多个专栏中?你能分享这个表格的布局和一些样本数据吗?我猜测一个游标循环遍历这个表并动态地执行语句就可以做到这一点。 – JNevill

+0

@Andrew:是的,我在表中有SELECT语句。我想运行这些sql查询并用查询结果填充另一个表。 –

回答

0

这里有一个漂亮的准系统程序,用于解决这个问题。

  1. 我们使用游标来遍历保存SQL语句
  2. 我们采用第二光标同时通过第一游标循环动态执行的SQL字符串您的源表:因为它变得有点毛毛并将该SQL查询的结果FETCH到一个变量中。

我会怀疑你会遇到各种各样的错误,而得到这个设置,但我相信这是相当接近的工作过程:

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 
+0

感谢您提供此解决方案。 –

+0

我在开发时创建了存储过程。我无法理解SQL语句如何运行并在sqlResults中获取结果。我想知道“PREPARE S1 FROM sqlQuery”;正在从查询中获取结果。 –

+0

'sqlQuery'是一个正在填充第一个游标(从您的表)中的记录的SQL语句的varchar /字符串。我们创建了一个从语句“S1”创建的游标。 'sql'从'sqlQuery'中的sql语句中“准备好”。一旦该语句“准备好”,我们就可以打开“C1”游标,并使用'sqlQuery'字符串中的记录填充's1'语句。为了动态执行存储在列中的sql语句,我们需要花费很多时间。 – JNevill

相关问题