首页 > 解决方案 > 如何使用 sql 查询作为字符串参数?

问题描述

我有查询执行没有错误或问题

select * from table(get_values_in_rows('word1:word2:word3:word4:word5:word6'));

但是当我使用查询作为字符串参数时,例如它不执行

select * from table(get_values_in_rows(
'select branch_id from nazim_shift where user_level=5 and lower(nazim_login_id)=:value1'
));

著名的:

create or replace function get_values_in_rows(pv_colon_values in varchar2) return t_rows_tab is
list_values t_rows_tab := t_rows_tab();
begin

  for i in (SELECT distinct REGEXP_SUBSTR(pv_colon_values, '[^:]+', 1, LEVEL) colon_values FROM dual
  CONNECT BY REGEXP_SUBSTR(pv_colon_values, '[^:]+', 1, LEVEL) IS NOT NULL)
  loop
  list_values.extend;
  list_values(list_values.last) := t_rows(i.colon_values);
  end loop;

  return list_values;

end get_values_in_rows;

select branch_id from nazim_shift where user_level=5 and lower(nazim_login_id)=:value1

上面的查询将返回冒号分隔的值

我们正在使用 oracle 11g

标签: sqloracleoracle11goracle-sqldeveloper

解决方案


您需要将选定的 branch_id 传递给函数:

select column_value as branches
from   nazim_shift ns cross join table(get_values_in_rows(ns.branch_id))
where  user_level = 5
and    lower(nazim_login_id)='def';

我可能会将拆分函数写为:

create or replace function get_values_in_rows
    ( p_string in varchar2
    , p_delimiter in varchar2 default ':' )
    return t_rows_tab
as
    list_values t_rows_tab := t_rows_tab();
begin
    select distinct regexp_substr(p_string, '[^'||p_delimiter||']+', 1, rownum)
    bulk collect into list_values
    from   dual
    connect by rownum <= regexp_count(trim(p_delimiter from p_string),p_delimiter) +1;

    return list_values;
end get_values_in_rows;

但是我也会避免将 CSV 列表存储在列中。最好有第二个表,其中各个分支 ID 存储为行,或者如果必须,使用嵌套表或可变数组列。


推荐阅读