-- Author: happyflsytone
-- Date:2008-11-05 14:59:34
-- 创建函数
create function [dbo].[split_str]
(
@s varchar(8000), --包含多个数据项的字符串
@index int, --要获取的数据项的位置
@split varchar(10) --数据分隔符
)
returns varchar(100)
as
begin
if @s is null return(null)
begin
declare @splitlen int
select @splitlen=len(@split+'A')-2
end
while @index>1 and charindex(@split,@s+@split)>0
begin
select @index=@index-1,@s=stuff(@s,1,charindex(@split,@s+@split)+@splitlen,'')
end
return(isnull(left(@s,charindex(@split,@s+@split)-1),''))
end
--测试示例
select dbo.split_str('1-2-3-4',3,'-')
--运行结果
/*
3
*/
本文介绍了一个用于SQL的自定义函数,该函数可以将带有特定分隔符的字符串拆分成多个独立的部分,并允许用户指定所需的特定部分。通过提供的示例,展示了如何创建此函数以及如何使用它来从字符串'1-2-3-4'中提取第三个元素。

被折叠的 条评论
为什么被折叠?



