假设我有包含列的Table1:id1, name, column_name
和一个包含列的Table2:id2, id1 (fk), col1, col2, col3, ..., colN
这只是我正在寻找的一个简单的例子。实际上,在这两个表之间有多个表。
column_name下的Table1中的值是字符串值"col1", "col2", "col3", ..., "colN"。
本质上,我想要一个select语句,它将字符串"col1", "col2", ...替换为列1、列2、...来自Table2。
谢谢。
发布于 2014-05-13 01:15:55
如果您知道模式,并准备对所有可能的列名进行硬编码,那么您可以使用case语句来强制执行:
select case lower(t1.column_name)
when 'col1' then col1
when 'col2' then col2
when 'col3' then col3
...
when 'coln' then coln
end as result
from table1 t1
join table2 t2 on t2.id1 = t1.id1
where t1.id1 = 1;如果您需要它更灵活,那么您将需要使用动态SQL。您说要显示它,并且已经使用SQL Developer标记了该问题,因此这可能意味着将输出显示在SQL Worksheet script output窗口中-这可以使用dbms_output来完成
set serveroutput on
declare
l_id1 number := 1;
l_column_name table1.column_name%type;
l_cur_sql varchar2(80);
l_cur sys_refcursor;
l_result number;
begin
select column_name into l_column_name from table1 where id1 = l_id1;
l_cur_sql := 'select ' || l_column_name || ' from table2 '
|| 'where id1 = :id1';
open l_cur for l_cur_sql using l_id1;
loop
fetch l_cur into l_result;
exit when l_cur%notfound;
dbms_output.put_line(l_result);
end loop;
close l_cur;
end;
/或者,您可以使用SQL*Plus/SQL Developer绑定变量处理来简化游标处理,而不依赖于dbms_output
var cur refcursor;
var id number;
exec :id := 1;
declare
l_column_name table1.column_name%type;
l_cur_sql varchar2(80);
begin
select column_name into l_column_name from table1 where id1 = :id;
l_cur_sql := 'select ' || l_column_name || ' from table2 '
|| 'where id1 = :id1';
open :cur for l_cur_sql using :id;
end;
/
print cur它们实际上都在做同样的事情。将列名从table1获取到一个本地变量中,并使用它创建一条动态SQL语句,以便从table2中选择该列。您可以通过直接从table1查询创建动态SQL语句来进一步简化它:
declare
l_cur_sql varchar2(80);
begin
select 'select ' || column_name || ' from table2 ' || 'where id1 = :id1'
into l_cur_sql
from table1
where id1 = :id;
open :cur for l_cur_sql using :id;
end;
/但我认为分两个阶段会稍微清楚一点。
发布于 2014-05-13 00:32:44
下面的select将通过表1上的主键和表2上的外键来连接表。select * from table1 inner join table2 on table1.id1 = table2.id1;
如果我知道你的想法,下一步是用另一个表中的数据替换数据。
为此,您可以编写一个脚本。
I整数;
开始
for I in (select * from table1 inner join table2 on table1.id1 = table2.id1)循环
update table1
set table1.col1 = i.col2
where id1 = i.id1;结束循环;
结束;
当然,为了您的情况,您必须更改此语句。
https://stackoverflow.com/questions/23612731
复制相似问题