Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL: variables used in place of table names

Tags:

sql

oracle

plsql

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.

like image 623
OrangeGrover Avatar asked Jul 23 '12 23:07

OrangeGrover


1 Answers

  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.

like image 61
Justin Cave Avatar answered Oct 31 '22 17:10

Justin Cave