简体   繁体   English

Select 列为 Oracle SQL 中的列

[英]Select list as column in Oracle SQL

I would like to append a few rows to an already existing table (15 rows to be precise).我想 append 几行到一个已经存在的表(准确地说是 15 行)。 What is the quickest way to do this?最快的方法是什么?

This works, but it seems redundant.这行得通,但似乎是多余的。

select person_id from people_table
union all
select '0010' as person_id from dual
union all
select '0019' as person_id from dual
union all
select '0085' as person_id from dual

I was wondering if there's a solution along the lines of:我想知道是否有以下解决方案:

select person_id from people_table
union all
select ('0010','0019','0085') as person_id from dual

Please note that I want to preserve the leading zeros for each element in my list.请注意,我想为列表中的每个元素保留前导零。 This post is almost what I'm looking for , but it converts each element to integers and drops the leading zeros. 这篇文章几乎是我正在寻找的,但它将每个元素转换为整数并删除前导零。

You need to use the hiearchy query as follows:您需要使用 hiearchy 查询,如下所示:

select person_id from people_table
union all
select regexp_substr('0010,0019,0085','[^,]+',1,level) 
  from dual
connect by  level <= length (regexp_replace('0010,0019,0085', '[^,]+'))  + 1 ;

Please use below query using regular expression,请使用正则表达式使用以下查询,

select person_id from people_table
union all
select distinct  trim(regexp_substr(('0010,0019,0085'),'[^,]+', 1, level) ) as person_id
 from dual
 connect by regexp_substr(('0010,0019,0085'), '[^,]+', 1, level)
 order by level;

You can use a system-provided collection type;您可以使用系统提供的集合类型; you select from it using the TABLE operator (even that is no longer necessary since Oracle 12, as I demonstrate below).您使用TABLE运算符从中获取 select(即使自 Oracle 12 以来不再需要,如下所示)。 Note that the column name is COLUMN_NAME - that is the name Oracle chose when they created the system-provided type.请注意,列名称是COLUMN_NAME - 这是 Oracle 在创建系统提供的类型时选择的名称。

Let's create a small table for testing:让我们创建一个小表进行测试:

create table people_table (person_id varchar2(10), person_name varchar2(10));

insert into people_table (person_id, person_name) values ('2003', 'Maria');
insert into people_table (person_id, person_name) values ('2005', 'Peter');

Then, here is how you can do what you wanted:然后,这里是你可以做你想做的事:

select person_id from people_table
union all
select column_value from sys.odcivarchar2list('1000', '1001', '1002')
;

PERSON_ID
---------
2005
2003
1000
1001
1002

Do a Google search for SYS.ODCIVARCHAR2LIST (and similar SYS.ODCINUMBERLIST ) if you are not familiar with it;如果您不熟悉SYS.ODCIVARCHAR2LIST (和类似的SYS.ODCINUMBERLIST ),请在 Google 上进行搜索; it's quite useful.它非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM