Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

oracle - how to pass a table name as parameter to stored procedure?

Is it possible to create a rowtype for a table name which is passed as a parameter to a Stored-Procedure and also how do i know the columns to address them in the DBMS_OUUTPUT.PUT_LINE() statement.

The end user can give any user name(schema) and table name

I want to do something as below but it does not work.

 CREATE OR REPLACE PROCEDURE SP_PASS(USER_NAME VARCHAR2,TAB_NAME IN VARCHAR2)
 AS
    TYPE REF_CUR IS REF CURSOR;
    V_ARR REF_CUR;
    V_SQL VARCHAR(200);
    V_ROWTYPE USER_NAME.TAB_NAME%ROWTYPE;
 BEGIN
     V_SQL := 'SELECT * FROM '||USER_NAME||'.'||TAB_NAME;
     OPEN V_ARR FOR V_SQL;
     LOOP
     FETCH V_ARR INTO V_ROWTYPE;
     EXIT WHEN V_ARR%NOT FOUND;
     DBMS_OUTPUT.PUT_LINE(V_ROWTYPE.COL1||','||V_ROWTYPE.COL2||','||V_ROWTYPE.COL3);
     END LOOP;
     CLOSE V_ARR;
END;

Let me know if it is possible .

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't create a %ROWTYPE variable for an unknown table and you can't statically refer to column names when you don't know the table name at compile time.

You can use the dbms_sql package to deal with completely dynamic SQL statements. You'll need to prepare the SQL statement, describe the columns to find out the number of columns and their data types, bind appropriate variables, and then fetch the data. It's a much more cumbersome way of writing code than the example you posted but it gives you extreme flexibility.

There are a number of examples of using the dbms_sql package in the documentation I linked to. You may also want to check out Tom Kyte's dump_csv function which writes the result of an arbitrary query to a CSV file using UTL_FILE. If you really want to write the data to DBMS_OUTPUT, you could simply replace the UTL_FILE calls with DBMS_OUTPUT. But I'm pretty sure you want to do something more useful than just writing the data to the DBMS_OUTPUT buffer so Tom's procedure is probably closer to what you're really trying to accomplish.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...