【原创】扩展函数-SPLIT 欢迎转帖
在postgreSQL中,系统默认提供了SPLIT函数,提供非常实用的功能,将字符串按照指定的分隔符转换成一个集合,但在SQL SERVER中并没有提供,以下是本人扩展的SPLIT函数
函数主体代码:
-- =============================================
-- Author: DB惩罚者
-- Editor: DB惩罚者
-- ALTER date: 2008-03-28
-- Description: 将字符串按照指定分隔符转换为集合
-- ---------------------------------------------
-- Alter date:
-- Alter Log: 将字符串按照指定分隔符转换为集合
-- ---------------------------------------------
-- DEMO 1: select * from Split('a,b,c,',',' )
-- DEMO 2: select * from Split('a,,b,,c,, ',',,')
-- DEMO X:
-- ---------------------------------------------
-- Test Select:
-- Module Path:
-- Key Word: 公共 SPLIT 列表
-- =============================================
CREATE FUNCTION Split
(
-- Add the parameters for the function here
@str varchar(max)--目标字符串
,@char varchar(2000)--分隔符
)
RETURNS
@t TABLE
(
-- Add the column definitions for the TABLE variable here
id int identity(1,1)
,name varchar(max)
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
set @char='%'+@char+'%'
if(patindex(@char,@str)=0)
begin
insert into @t values (@str)
RETURN
end
else
begin
declare @s varchar(max)
set @s=''
while(patindex(@char,@str)>0)
begin
set @s=substring(@str,0,patindex(@char,@str))
insert into @t values(@s)
set @str=substring(@str,patindex(@char,@str)+len(replace(@char,'%','')),len(@str)-patindex(@char,@str)+1)
end
--if(len(@str)>0 and patindex(@char,@str)=0)
--begin
insert into @t values(@str)
--end
end
RETURN
END
浙公网安备 33010602011771号