根据条件将值连接到SELECT

时间:2018-08-06 15:41:02

标签: sql select plsql insert-into

我需要在表中插入一个隐含值列表,但是如果p_is_broker变量为true,则需要添加第一个值。为了简单起见,我们说这是真的。

insert into exports (session_id, row_sequence, row_data)
select token,
       1, 'Manager'
          ||','||'Company'
          ||','||'Driver Name'
          ||','||'Registration'
          ||','||'Vehicle'
from dual
union
select token,
       rownum + 1,
       '"'||replace(manager,'"','""')
          ||'","'||replace(company,'"','""')
          ||'","'||replace(driver_name,'"','""')
          ||'","'||replace(registration,'"','""')
from table(cast (p_data as data_t));

如果p_is_broker为真,如何插入“经理”?

我已经尝试过类似的操作,但是它不起作用。

 insert into exports (session_id, row_sequence, row_data)
 select token,
        1, (CASE WHEN p_is_broker THEN 'Manager' END)
            ||','||'Company'
            ||','||'Driver Name'
            ||','||'Registration'
            ||','||'Vehicle'
 from dual;

这很棘手,因为如果要有“经理”,我们就需要第一个||','||

1 个答案:

答案 0 :(得分:2)

在案例中移动逗号:

insert into session_csv_Exports (session_id, row_sequence, row_data)
select
  token,
  1,
  (CASE WHEN p_is_broker = 'Y' THEN 'Manager,' ELSE '' END)
  ||'Company'
  ||','||'Driver Name'
  ||','||'Registration'
  ||','||'Vehicle'
from dual;

此外,我无法想到将文字文字串联起来的任何理由。您应该简化为:

insert into session_csv_Exports (session_id, row_sequence, row_data)
select
  token,
  1,
  (CASE WHEN p_is_broker THEN 'Manager,' ELSE '' END)
  || 'Company,Driver Name,Registration,Vehicle'
from dual;