sqlServer中的split分隔函数
-- 1. 方法 连续二个以上的分隔符的作一个处理
-- =============================================
-- Author: <jason>
-- Create date: <2009-11-12>
-- Description: <分解字符串>
-- =============================================
---执行
-- SELECT * from dbo.Split_String ('a,b,eeec,,,,,,,d,,,,,we333r',',')
ALTER FUNCTION [dbo].[Split_String]
(
@split_string varchar(max), --要进行分解的字符串
@tag_string varchar(10) --分解标志
)
RETURNS
@split_table TABLE
(
split_value varchar(200)
)
AS
BEGIN
declare @temp_string varchar(max)
declare @start_index int
declare @end_index int
while 1=1
begin
set @start_index = 0
select @end_index = CharIndex(@tag_string,@split_string,@start_index)
--PRINT CharIndex(',','a44b,c55,d,we3r',6)
if @end_index <> 0
begin
set @temp_string = Substring(@split_string,@start_index,@end_index)
--PRINT Substring('a44b,c,d,we3r',6,7)
if @temp_string is not null and @temp_string <> ''
insert into @split_table(split_value) values(@temp_string)
set @start_index = @end_index + 1
set @split_string = Substring(@split_string,@start_index,len(@split_string))
-- PRINT Substring('a44b,c,d,we3r',6,len('a44b,c,d,we3r'))
end
else
begin
if @split_string is not null and @split_string <> ''
insert into @split_table(split_value) values(@split_string)
--退出while环循
break
end
end
RETURN
END
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
----方法2--------------------------------
-----------------------------------------
--在SQL中分割字符串 就是Split
----分割字符串
--创建函数
create function split
(
@SourceSql varchar(8000),
@StrSeprate varchar(10)
)
returns @temp table(F1 varchar(100))
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>''
insert @temp values(@SourceSql)
return
end
--执行
go
select * from split('01,,,02,03,dd,ss',',')