在运行时确定SQL From子句?

问题描述 投票:0回答:1

我有一个table1,其中包含一个列,其中存储了其他表的名称。根据table1中的值,查询应该提取与其中给出的表名对应的数据。

例如,让存储tablename的表为tablelist(tablename,tableid)

让名称存储在表list.table名称中的其他表为A,B,C

基于给定的输入参数tableid,如果tablename中存储的值为“A”,则查询应提取相当于以下内容的结果:

Select A.name from A;

如果是'B',查询应该是:

Select B.type from B;

如果是'C',查询应该是:

Select C.msg from C;

如何将其作为单个查询接受表id作为输入?

请指教

sql oracle
1个回答
1
投票

你可以尝试case when结构:

select case tableid 
       when 'A' then (select name from a) 
       when 'B' then (select type from b)
       when 'C' then (select msg  from c) 
       end
  from tbl

一些数据示例:

with 
  tablelist(tablename, tableid) as (
      select 'A', 1 from dual union all
      select 'B', 2 from dual union all
      select 'B', 7 from dual union all
      select 'C', 3 from dual ), 
  a(name) as (select 'Chris' from dual),
  b(type) as (select 'T800'  from dual),
  c(msg)  as (select 'Hello' from dual)
select case tablename
       when 'A' then (select name from a) 
       when 'B' then (select type from b)
       when 'C' then (select msg  from c) 
       end as value
  from tablelist
  where tableid = 7

结果T800

© www.soinside.com 2019 - 2024. All rights reserved.