本文共 2306 字,大约阅读时间需要 7 分钟。
create function f_split(@c varchar(2000),@split varchar(2)) returns @t table(col varchar(20)) as begin while(charindex(@split,@c)<>0) begin insert @t(col) values (substring(@c,1,charindex(@split,@c)-1)) set @c = stuff(@c,1,charindex(@split,@c),'') end insert @t(col) values (@c) return end go select * from dbo.f_split('dfkd,dfdkdf,dfdkf,dffjk',',') drop function f_split
CREATE function Get_StrArrayLength(@str varchar(1024), --要分割的字符串@split varchar(10) --分隔符号)returns intasbegindeclare @location intdeclare @start intdeclare @length int set @str=ltrim(rtrim(@str))set @location=charindex(@split,@str)set @length=1while @location<>0begin set @start=@location+1 set @location=charindex(@split,@str,@start) set @length=@length+1endreturn @lengthend调用示例:
select dbo.Get_StrArrayLength('78,1,2,3',',')返回值:4
CREATE function Get_StrArrayStrOfIndex(@str varchar(1024), --要分割的字符串@split varchar(10), --分隔符号@index int --取第几个元素)returns varchar(1024)asbegindeclare @location intdeclare @start intdeclare @next intdeclare @seed int set @str=ltrim(rtrim(@str))set @start=1set @next=1set @seed=len(@split) set @location=charindex(@split,@str)while @location<>0 and @index>@nextbegin set @start=@location+@seed set @location=charindex(@split,@str,@start) set @next=@next+1endif @location =0 select @location =len(@str)+1 --这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号。 return substring(@str,@start,@location-@start)end
select dbo.Get_StrArrayStrOfIndex('8,9,4',',',2)返回值:9
declare @str varchar(50)set @str='1,2,3,4,5'declare @next int set @next=1while @next<=dbo.Get_StrArrayLength(@str,',')beginprint dbo.Get_StrArrayStrOfIndex(@str,',',@next)set @next=@next+1end
select f1,f2,f3,left(A,charindex('_',A)-1)from 表名 order by left(A,charindex('_',A)-1)
转载地址:http://cpfkl.baihongyu.com/