首页 > 数据库 > SQL Server > 正文

教你在SQL Server数据库中拆分字符串函数

2024-08-31 00:52:31
字体:
来源:转载
供稿:网友
SQL Server数据库中拆分字符串函数的具体方法:

CREATE   FUNCTION uf_StrSplit '1.1.2.50','.'(@origStr varchar(7000),   --待拆分的字符串@markStr varchar(100))    --拆分标记,如','RETURNS @splittable table(str_id    varchar(4000) NOT NULL, --编号IDstring    varchar(2000) NOT NULL --拆分后的字符串)AS BEGINdeclare @strlen int,@postion int,@start int,@sublen int,@TEMPstr varchar(200),@TEMPid intSELECT @strlen=LEN(@origStr),@start=1,@sublen=0,@postion=1,@TEMPstr='',@TEMPid=0if(RIGHT(@origStr,1)<>@markStr )beginset @origStr = @origStr + @markStrendWHILE((@postion<=@strlen) and (@postion !=0))BEGINIF(CHARINDEX(@markStr,@origStr,@postion)!=0)BEGINSET @sublen=CHARINDEX(@markStr,@origStr,@postion)-@postion; ENDELSEBEGINSET @sublen=@strlen-@postion+1;ENDIF(@postion<=@strlen)BEGINSET @TEMPid=@TEMPid+1;SET @TEMPstr=SUBSTRING(@origStr,@postion,@sublen);INSERT INTO @splittable(str_id,string) values(@TEMPid,@TEMPstr)IF(CHARINDEX(@markStr,@origStr,@postion)!=0)BEGINSET @postion=CHARINDEX(@markStr,@origStr,@postion)+1ENDELSEBEGINSET @postion=@postion+1ENDENDENDRETURNEND

例如:select * from uf_StrSplit('1,1,2,50',',')

输出结果:

str_id      string1             12             13             24            50

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表