Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from table, name is stored in the field

Tags:

sql

oracle

How can I join some data from some table whose name is a field of the dataset?

Like this:

SELECT *
FROM dataset
INNER JOIN dataset.table_name 
ON dataset.param_id = (dataset.table_name).id_(dataset.table_name)
like image 560
c4rrt3r Avatar asked Oct 22 '22 23:10

c4rrt3r


1 Answers

You will have to construct the select statement as a string using T-SQL. Then, use the execute command to run it. For example:

DECLARE @sql VARCHAR(MAX);
DECLARE @table_name VARCHAR(100);
SET @table_name = (SELECT TOP 1 table_name FROM dataset)   ' TODO set criteria correctly here
SELECT @sql = 'SELECT * FROM dataset INNER JOIN ' & @table_name & ' ON dataset.param_id = ' & @table_name & '.id_' & @table_name & ';'
EXEC (@sql)

Update

This is the syntax for Oracle (quoted from Andrewst's answer here):

DECLARE
  TYPE rc_type REF CURSOR;
  rc rc_type;
  table_rec table%ROWTYPE;
BEGIN
  OPEN rc FOR 'select * from table';
  LOOP
    FETCH rc INTO table_rec;
    EXIT WHEN rc%NOTFOUND;
    -- Process this row, e.g.
    DBMS_OUTPUT.PUT_LINE( 'Name: '||table_rec.name );
  END LOOP;
END;

http://www.dbforums.com/oracle/718534-ms-sql-exec-equivalent.html

like image 105
McGarnagle Avatar answered Nov 03 '22 21:11

McGarnagle