2017-08-28 154 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

相關問題