类似于 aa/bb/cc/dd/ee/ff 得到 aa cc ee
aaa/bbb/ccc/ddd/eee/ff/ggg 得到 aaa ccc eee
split后取得斜杠之间的位置是固定的
以下是参考函数
2:================================================================
create FUNCTION dbo.splitString
(
@string VARCHAR(MAX),
@delimiter CHAR(1),
@rep int =1
)
RETURNS varchar(10)
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
declare @ic int
set @ic = 1
WHILE @start < LEN(@string) + 1 BEGIN
if(@ic = @rep) return substring(@string, @start, @end-@start)
IF @end = 0
SET @end = LEN(@string) + 1
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
set @ic = @ic + 1
END
return null
END
create table ta(col varchar(30))
insert into ta values('[ad][ba][daf]')
insert into ta values('[erf][afda][dasfasdf]')
insert into ta values('[fas][fase][reb]')
select dbo.SplitString(col, ']', 1)+']' as col1,
dbo.SplitString(col, ']', 2)+']' as col2,
dbo.SplitString(col, ']', 3)+']' as col3
from ta
col1 col2 col3
----------- ----------- -----------
[ad] [ba] [daf]
[erf] [afda] [dasfasdf]
[fas] [fase] [reb]
====================================================================
3:=================================================================
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE SPECIFIC_NAME = N'Split' )
DROP FUNCTION Split
GO
CREATE FUNCTION dbo.Split
(
@ItemList VARCHAR(4000),
@delimiter VARCHAR(10)
)
RETURNS @IDTable TABLE (Item VARCHAR(50))
AS
BEGIN
WHILE CHARINDEX(@delimiter, @ItemList)>0
BEGIN
INSERT @IDTable SELECT LEFT(@ItemList,CHARINDEX(@delimiter,@ItemList)-1)
SET @ItemList=STUFF(@ItemList,1,CHARINDEX(@delimiter,@ItemList),'')
END
INSERT @IDTable SELECT @ItemList
RETURN
END
GO
SELECT * FROM dbo.SPLIT('aaaa,bbb,ccc,eee',',')
GO
=====================================================================
4:==================================================================
create function dbo.fn_split
(
@inputstr varchar(8000),
@seprator varchar(10)
)
returns @temp table (a varchar(200))
as
begin
declare @i int
set @inputstr = rtrim(ltrim(@inputstr))
set @i = charindex(@seprator, @inputstr)
while @i >= 1
begin
insert @temp values(left(@inputstr, @i - 1))
set @inputstr = substring(@inputstr, @i + 1, len(@inputstr) - @i)
set @i = charindex(@seprator, @inputstr)
end
if @inputstr <> '\'
insert @temp values(@inputstr)
return
end
go
--调用
declare @s varchar(1000)
set @s='1,2,3,4,5,6,7,8,55'
select * from dbo.fn_split(@s,',')
drop function dbo.fn_split
=====================================================================
5:==================================================================
CREATE FUNCTION f_splitSTR(
@s varchar(8000), --待分拆的字符串
@split varchar(10) --数据分隔符
)RETURNS TABLE
AS
RETURN(
SELECT col=CAST(SUBSTRING(@s,ID,CHARINDEX(@split,@s+@split,ID)-ID) as varchar(100))
FROM tb_splitSTR
WHERE ID<=LEN(@s+'a')
AND CHARINDEX(@split,@split+@s,ID)=ID)
GO
=====================================================================