Oracle:将字符串拆分为行

时间:2011-08-01 21:43:17

标签: sql oracle

我们来看看这个问题:

WITH temp as SELECT '123455' colum from dual
SELECT * FROM big_table WHERE cod IN (SELECT colum from temp)
UNION ALL
SELECT * FROM big_table2 WHERE cod IN (SELECT colum from temp)

我想搜索一个值列表以及我可以查找一个值,但是如何构建一个行列表而不必编写大量的UNION?

3 个答案:

答案 0 :(得分:3)

如果您有可用的字符串表类型,则以下脚本可能会执行您想要的操作

create table big_table
(
cod varchar2(4000)
);

create table big_table2
(
cod varchar2(4000)
);

insert into big_table (cod) values ('12345');
insert into big_table (cod) values ('12346');
insert into big_table (cod) values ('12347');

insert into big_table (cod) values ('12345');
insert into big_table (cod) values ('12348');
insert into big_table (cod) values ('12349');

--Example usage of the custom defined type stringarray
SELECT column_value from table(stringarray('12345','12348'));

WITH temp as (SELECT column_value from table(stringarray('12345','12348')))
SELECT * FROM big_table WHERE cod IN (SELECT column_value from temp)
UNION ALL
SELECT * FROM big_table2 WHERE cod IN (SELECT column_value from temp);

drop table big_table;
drop table big_table2;

您可以像这样创建stringarray类型

CREATE OR REPLACE TYPE STRINGARRAY as table of varchar2(30)

我希望能回答你的问题。

答案 1 :(得分:0)

我不确定Oracle是否支持它(或者如果这正是你所要求的),但是如果它像DB2一样,你可以使用你的Common Table Expression来构建你的值列表... < / p>

WITH temp (colum) as (VALUES '123456', '789012', '345678')
SELECT * FROM big_table WHERE cod IN (SELECT colum from temp)
UNION ALL
SELECT * FROM big_table2 WHERE cod IN (SELECT colum from temp)

至于不必编写负载的UNIONS,我认为没有更好的方法来做你想要的......

答案 2 :(得分:0)

如果您正在搜索多个表,那么如果您想在单个集合操作中执行此操作,则无法避免使用UNION。

否则,您可以将一个表名数组传递给一个循环,然后只需动态写入然后运行sql。我宁愿亲自做工会......