gpt4 book ai didi

sql - 解析逗号分隔的字符串以生成Where子句中的IN字符串列表

转载 作者:行者123 更新时间:2023-12-01 21:59:52 25 4
gpt4 key购买 nike

我的存储过程接收一个以逗号分隔的字符串参数:

DECLARE @Account AS VARCHAR(200)
SET @Account = 'SA,A'

我需要从中做出这样的陈述:

WHERE Account IN ('SA', 'A')

执行此操作的最佳实践是什么?

最佳答案

创建此函数(sqlserver 2005+)

CREATE function [dbo].[f_split]
(
@param nvarchar(max),
@delimiter char(1)
)
returns @t table (val nvarchar(max), seq int)
as
begin
set @param += @delimiter

;with a as
(
select cast(1 as bigint) f, charindex(@delimiter, @param) t, 1 seq
union all
select t + 1, charindex(@delimiter, @param, t + 1), seq + 1
from a
where charindex(@delimiter, @param, t + 1) > 0
)
insert @t
select substring(@param, f, t - f), seq from a
option (maxrecursion 0)
return
end

使用此语句

SELECT *
FROM yourtable
WHERE account in (SELECT val FROM dbo.f_split(@account, ','))
<小时/>

将我的拆分函数与 XML 拆分进行比较:

测试数据:

select top 100000 cast(a.number as varchar(10))+','+a.type +','+ cast(a.status as varchar(9))+','+cast(b.number as varchar(10))+','+b.type +','+ cast(b.status as varchar(9)) txt into a 
from master..spt_values a cross join master..spt_values b

XML:

 SELECT count(t.c.value('.', 'VARCHAR(20)'))
FROM (
SELECT top 100000 x = CAST('<t>' +
REPLACE(txt, ',', '</t><t>') + '</t>' AS XML)
from a
) a
CROSS APPLY x.nodes('/t') t(c)

Elapsed time: 1:21 seconds

f_split:

select count(*) from a cross apply clausens_base.dbo.f_split(a.txt, ',')

Elapsed time: 43 seconds

这会随着运行的不同而改变,但你明白了

关于sql - 解析逗号分隔的字符串以生成Where子句中的IN字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17481479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com