How to select a table using a string in oracle?

Member

by lily , in category: MySQL , 3 months ago

How to select a table using a string in oracle?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 3 months ago

@lily 

To select a table using a string in Oracle, you can use dynamic SQL. Dynamic SQL allows you to construct SQL statements as strings and then execute them using the EXECUTE IMMEDIATE statement.


Here is an example of how you can select a table using a string in Oracle:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
DECLARE
    table_name VARCHAR2(50) := 'your_table_name';
    sql_query VARCHAR2(100);
    result VARCHAR2(100);

BEGIN
    sql_query := 'SELECT * FROM ' || table_name;
    EXECUTE IMMEDIATE sql_query INTO result;

    DBMS_OUTPUT.PUT_LINE(result);
END;


In the above example, replace 'your_table_name' with the actual name of the table you want to select from. The sql_query variable is constructed by concatenating the table name with the rest of the SQL statement. The EXECUTE IMMEDIATE statement is used to execute the dynamically constructed SQL query, and the result is stored in the result variable.


It is important to handle errors and security considerations when using dynamic SQL in Oracle. Be sure to validate input and use bind variables to prevent SQL injection attacks.