dreamontheway的技术之路

向着光明,我要一步一步往上爬。

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

sql把逗号分隔的字符串拆成临时表

sql把逗号分隔的字符串拆成临时表

    在与数据库交互的过程中,我们经常需要把一串ID组成的字符串当作参数传给存储过程获取数据。很多时候我们希望把这个字符串转成集合以方便用于in操作。 有两种方式可以方便地把这个以某种符号分隔的ID字符串转成临时表。

方式一:通过charindex和substring。

复制代码
代码
create function func_splitstring
(
@str nvarchar(max),@split varchar(10))
returns @t Table (c1 varchar(100))
as
begin
declare @i int
declare @s int
set @i=1
set @s=1
while(@i>0)
begin
set @i=charindex(@split,@str,@s)
if(@i>0)
begin
insert @t(c1) values(substring(@str,@s,@i-@s))
end
else begin
insert @t(c1) values(substring(@str,@s,len(@str)-@s+1))
end
set @s = @i + 1
end
return
end
复制代码

执行:select * from dbo.func_splitstring('1,2,3,4,5,6', ',')

结果:

     

方式二:通过XQuery(需要SQL Server 2005以上版本)。

复制代码
代码
create function func_splitid
(
@str varchar(max),@split varchar(10))
RETURNS @t Table (c1 int)
AS
BEGIN
DECLARE @x XML
SET @x = CONVERT(XML,'<items><item id="' + REPLACE(@str, @split, '"/><item id="') + '"/></items>')
INSERT INTO @t SELECT x.item.value('@id[1]', 'INT') FROM @x.nodes('//items/item') AS x(item)
RETURN
END
复制代码

执行:select * from dbo.func_splitid('1,2,3,4,5,6', ',')

结果:

    

阅读全文
类别:sql ado 存储过程 查看评论

posted on   dreamontheway  阅读(392)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示