Oracle PL/SQL提取列名并在select语句中使用
我不确定这是否可行,但我正试图用尽可能少的手工来完成这项工作 我有一个基于不同因素组合的150列表格。 我希望提取列名中的某个字符串 我已经做了下面的事情,这就是。这是我所拥有的一个基本例子Oracle PL/SQL提取列名并在select语句中使用,oracle,plsql,Oracle,Plsql,我不确定这是否可行,但我正试图用尽可能少的手工来完成这项工作 我有一个基于不同因素组合的150列表格。 我希望提取列名中的某个字符串 我已经做了下面的事情,这就是。这是我所拥有的一个基本例子 --Create the table Create Table temp (id number, Fac1_Fac2_Fac_3_Fac4_Fac5 number, Fac1_Fac6_Fac_3_Fac4_Fac5 number, Fac1_Fac6_Fac_
--Create the table
Create Table temp
(id number,
Fac1_Fac2_Fac_3_Fac4_Fac5 number,
Fac1_Fac6_Fac_3_Fac4_Fac5 number,
Fac1_Fac6_Fac_7_Fac4_Fac5 number,
Fac1_Fac9_Fac_3_Fac4_Fac5 number,
Fac1_Fac10_Fac_3_Fac4_Fac5 number,
Fac1_Fac2_Fac_3_Fac11_Fac5 number,
Fac1_Fac2_Fac_3_Fac4_Fac12 number,
Fac13_Fac2_Fac_3_Fac4_Fac5 number);
Insert into temp Values (1,35634,3243,343,564,56,4635,3,334);
Insert into temp Values (2,3434234,3243,343,564,56,435,3,34234);
Insert into temp Values (3,5555,3243,33,564,56,435,3,3434);
Insert into temp Values (4,34234,343,343,564,56,4335,3,34);
commit;
--Extract Column Names
Select * from (
Select COLUMN_NAME
from user_tab_cols
where lower(table_name) ='temp'
)
where column_name like '%FAC13%'
--This is what I want to automate.
Select id, FAC13_FAC2_FAC_3_FAC4_FAC5
From temp
--I want the column name to come fron the select statment above as there may be lots of names.
基本上,如果可能的话,我希望从表中选择列名中包含Fac13的所有行
谢谢我认为你不可能在一次查询中做到这一点。首先,可以将
提取列名查询
简化为一个查询作为游标,然后使用动态select语句,如下所示:
CREATE OR REPLACE proc_dyn_select IS
CURSOR c1 IS
SELECT column_name
FROM user_tab_cols
WHERE LOWER(table_name) ='temp' and column_name LIKE '%FAC13%';
cols c1%ROWTYPE;
sqlstmt VARCHAR2(2000);
BEGIN
OPEN c1;
LOOP
FETCH c1 into cols;
EXIT WHEN c1%NOTFOUND;
sqlstmt := sqlstmt ||cols.column_name||',';
END LOOP;
CLOSE c1;
sqlstmt := 'select '||substr(sqlstmt, 1, length(sqlstmt)-1)||' FROM temp';
EXECUTE IMMEDIATE sqlstmt;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('error '||sqlerrm);
END;
/
解释
首先,光标将存储满足您条件的列(来自表temp
,列名具有子字符串FAC13
。然后在执行部分(在开始之后
),您将使用存储在游标c1
中的列名动态构建查询。在循环的每一轮中,列名都作为字符串添加,并用逗号连接。因此,将构建一个列字符串,如下所示'col1,col2,col3,…coln',
。该字符串存储在sqlstmt变量中
循环结束后,通过添加关键字SELECT
、FROM
和table name来修改字符串以生成sql语句。但是,我们删除了sqlstmt
变量的最后一个字符,因为它是一个额外的逗号
executeimmediate
语句,将运行存储在sqlstmt
中的查询
通过使用过程,您可以始终传递参数,这样该过程就可以执行您想要的任何动态sql语句。请原谅我的无知,但您介意大致解释一下这是如何工作的吗?@GrantMcKinnon我尝试尽可能多地解释。希望这有帮助,谢谢,但这对您有帮助吗?我一直得到一个“缺失的o”r的游标部分出现“无效选项”错误query@GrantMcKinnon我刚刚在11g sql developer上用小表测试了它。它正在工作。这可能是因为我使用的是PL/sql developer吗?我也在使用11g,所以不确定为什么它不工作