2017-11-18 56 views
0

如何使用plsql中的函數/過程創建表,以便將表名稱作爲動態變量並使用提供的參數創建該表? A)我試過了:如何使用動態用戶輸入在plsql中使用函數/過程創建表

CREATE OR REPLACE PROCEDURE CREATE_TABLE IS 
UN VARCHAR2(20) :=&TABLE_NAME; 

BEGIN 
    CREATE TABLE UN(CUSTOMER_ID NUMBER,ORDER_DATE VARCHAR2(20),ORDER_MODE VARCHAR2(20),ORDER_STATUS NUMBER,SALES_REP_ID NUMBER,ORDER_TOTAL NUMBER, 
    PROMOTION_ID CHAR,ERROR_MESSAGE VARCHAR2(30),RECORD_STATUS CHAR); 
    end; 

    insert into UN(select distinct CUSTOMER_ID,TO_CHAR(TO_TIMESTAMP(ORDER_DATE),'DD-MM-YYYY'),UPPER(ORDER_MODE),UPPER(ORDER_STATUS),SALES_REP_ID,ORDER_TOTAL,PROMOTION_ID,ERROR_MESSAGE,RECORD_STATUS 
    FROM LIKHITH where ORDER_TOTAL >0 AND ORDER_TOTAL NOT LIKE '%.%'); 
    IF COUNT(CUSTOMER_ID)=9 THEN 
    (
    UPDATE LIKHITH SET (RECORD_STATUS='E' AND ERROR_MESSAGE='ERR') WHERE (ORDER_TOTAL<0 OR ORDER_TOTAL NOT LIKE '%.%'); 
    UPDATE LIKHITH SET RECORD_STATUS='P' WHERE (ORDER_TOTAL<0 AND ORDER_TOTAL NOT LIKE '%.%'); 
    UPDATE UN SET RECORD_STATUS='P'; 
    ) 
    END IF; 
    ) 
END; 
/
+0

即使PL/SQL具有'create table'(它沒有),它也無法編譯,因爲表'UN'無法在編譯時解析。然而,'&TABLE_NAME'將在編譯時解析(假設這是由支持替換變量的應用程序運行的,並使用'&'字符表示),這可能不是您想要的。 –

回答

1

您需要使用動態SQL。代碼中有許多冗餘的括號,這是不需要的。

另外這條線IF COUNT(CUSTOMER_ID)=9沒有意義。您應該從表格中進行選擇並進行比較。

CREATE OR REPLACE PROCEDURE CREATE_TABLE 
             ( un VARCHAR2) 
IS 
     v_count NUMBER; 
BEGIN 
     EXECUTE IMMEDIATE 'CREATE TABLE '|| 
     UN        || 
     '     
(      
CUSTOMER_ID NUMBER,       
ORDER_DATE VARCHAR2(20),       
ORDER_MODE VARCHAR2(20),       
ORDER_STATUS NUMBER,       
SALES_REP_ID NUMBER,       
ORDER_TOTAL NUMBER,       
PROMOTION_ID CHAR,       
ERROR_MESSAGE VARCHAR2(30),       
RECORD_STATUS CHAR     
)'; 
     EXECUTE IMMEDIATE 'insert into '|| 
     UN        || 
     '   
select distinct     
CUSTOMER_ID,     
TO_CHAR(TO_TIMESTAMP(ORDER_DATE),''DD-MM-YYYY''),     
UPPER(ORDER_MODE),     
UPPER(ORDER_STATUS),     
SALES_REP_ID,     
ORDER_TOTAL,     
PROMOTION_ID,     
ERROR_MESSAGE,     
RECORD_STATUS   
FROM     
LIKHITH   
where ORDER_TOTAL >0     
AND ORDER_TOTAL NOT LIKE ''%.%''' ; 
     EXECUTE IMMEDIATE 'SELECT COUNT(CUSTOMER_ID) FROM ' || 
     UN INTO v_count; 
     IF v_count = 9 THEN 
       UPDATE 
         LIKHITH 
       SET  RECORD_STATUS   ='E' , 
         ERROR_MESSAGE   ='ERR' 
       WHERE ORDER_TOTAL   <0 
         OR ORDER_TOTAL NOT LIKE '%.%'; 

     ELSE 
       UPDATE 
         LIKHITH 
       SET  RECORD_STATUS   ='P' 
       WHERE ORDER_TOTAL   <0 
         AND ORDER_TOTAL NOT LIKE '%.%'; 

       EXECUTE IMMEDIATE 'UPDATE '|| 
       UN       || 
       ' SET RECORD_STATUS=''P'''; 
     END IF; 
END; 
/

在編譯過程中不要傳遞表名,因爲您正在嘗試。在執行過程中如下所示通過它。

EXEC CREATE_TABLE('&table_name'); 
+0

謝謝...對於答案... –

相關問題