我收到以下声明:
SELECT XYZ FROM ABC WHERE ID IN (123)
目前我将123作为配置参数放在一个单独的表中:
SELECT XYZ FROM ABC WHERE ID IN (SELECT CONTENT FROM c_configuration WHERE IDENTIFIER = "ID")
现在c_configuration参数的内容已更改为“123,456”。
有没有更好的方法然后将字段内容拆分为“,”并将它们插入数组并将数组放入WHERE ID IN ( ARRAY )
部分?
提前谢谢你 马特
答案 0 :(得分:3)
尝试以下代码:
SELECT XYZ
FROM ABC
WHERE ID IN
(
SELECT DISTINCT TO_NUMBER(REGEXP_SUBSTR(CONTENT,'[^,]+', 1, level))
FROM c_configuration
WHERE IDENTIFIER = 'ID'
CONNECT BY REGEXP_SUBSTR(CONTENT, '[^,]+', 1, level) IS NOT NULL
)
答案 1 :(得分:1)
您必须拆分csv值或使用动态sql。
答案 2 :(得分:1)
你可以创建一个这样的函数:
create function dbo.fn_SplitString
(
@str nvarchar(max),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
substring(
@str,
a,
case when b > 0 then b-a ELSE LEN(@str) end)
AS id
from tokens
);
此函数返回一个“数组/集”,您可以在“where in”语句中使用
select *
from myTable
where ID in (
select id
from fn_fn_SplitString(select CONTENT from c_configuration where IDENTIFIER = "ID",','))