sql - 如何动态地将列名传递给查询?
问题描述
以下是我的问题和所需的解决方案。
查询1:
Select colnames from table1;
Query1 Result:
col1
col2
col3
col4
查询2:
Select a1.*
from table2 a1;
-- should translate to
select a1.col1, a1.col2, a1.col3, a1.col4 from table2 a1;
我的第一个查询将给出列名列表,我需要在第二个查询中将 .* 替换为这些列名。我怎样才能做到这一点?
解决方案
您正在寻找动态 SQL。这个想法是从 SQL 查询的结果中生成查询字符串。然后,您可以使用execute immediate
.
在您的用例中,这看起来像:
declare
p_sql varchar2(100);
begin
select
'select '
|| listagg('a1.' || colnames, ', ') within group(order by colnames)
|| ' from table2 a1'
into p_sql
from table1;
dbms_output.put_line('sql: ' || p_sql); -- debug
execute immediate p_sql; -- execute
end;
/
对于您的示例数据,这会生成:
dbms_output:
sql: select a1.col1, a1.col2, a1.col3, a1.col4 from table2 a1
推荐阅读
- android-studio - Android Studio 北极狐将 testRunner 设置为 GRADLE 而不是 PLATFORM
- jquery - Asp.Net Core-Validation 并使用 Ajax 提交表单?
- angular - 在订阅中编辑后未定义的属性
- java - 如何设置点的坐标?
- angular - 从“css-loader!./test.css”导入测试返回字符串
- c - 我有两个相邻的while循环,但是当第一个while循环更改输入时,如何使用原始输入运行第二个while循环?
- github-actions - 为什么这不会在拉取请求推送提交更新时触发?
- javascript - 聚焦jQuery
- android - xml 视图的重复资源 ID
- html - 如何制作外部网站的搜索表单?