12

I am converting a MSSQL script to Oracle, and I haven't been able to figure out the syntax to use a variable in place of a table name or column.

Here is a simple example that I've been try to make work in Oracle SQL Developer so I can better understand the syntax:

 set serveroutput on format wrapped;
declare 
  VR_TABLE VARCHAR2(256);
  VR_UPDATE VARCHAR2(256);
begin
  VR_TABLE :='SYSTEM_STATUS';
  EXECUTE IMMEDIATE 'select UPDATE_VERSION INTO VR_UPDATE from ' || VR_TABLE || 'where rownum < 2 ;'
end;

Where VR_TABLE is the variable table name that will get changed each iteration of the loop. Can somebody point out what I'm doing wrong, or link me to a site that would be useful for me to read? I've read a few tutorials on this, but I haven't had any luck thus far.

4

2 回答 2

21
  1. You need to have a space between the table name and the subsequent WHERE clause
  2. The INTO needs to be part of the EXECUTE IMMEDIATE, not part of the dynamic SQL statement.
  3. The dynamic SQL statement should not have a trailing semicolon
  4. The EXECUTE IMMEDIATE statement should end with a semicolon

Putting those together, something like this should work

declare 
  VR_TABLE VARCHAR2(256);
  VR_UPDATE VARCHAR2(256);
begin
  VR_TABLE :='SYSTEM_STATUS';
  EXECUTE IMMEDIATE 'select UPDATE_VERSION from ' || VR_TABLE || ' where rownum < 2'
               INTO VR_UPDATE;
end;

Of course, since you're not doing anything with VR_UPDATE, nothing will be displayed when this anonymous block is executed.

于 2012-07-24T00:09:00.977 回答
1

INTO part of the query should not be directly included in the query string.

Syntax

EXECUTE IMMEDIATE(<SQL>)
[INTO<variable>]
[USING <bind_variable_value>]

The above syntax shows EXECUTE IMMEDIATE command.

Clause INTO is optional and used only if the dynamic SQL contains a select statement that fetches values. The variable type should match with the variable type of the select statement.

Clause USING is optional and used only if the dynamic SQL contains any bind variable.

https://www.guru99.com/dynamic-sql-pl-sql.html#2

You can visit this site for a better understanding of Dynamic SQL.

于 2021-04-29T12:27:58.553 回答