sqlserver split函数
发布时间:2020-12-12 14:20:39 所属栏目:MsSql教程 来源:网络整理
导读:create FUNCTION [ dnt_split ] (? @splitstring NVARCHAR ( 4000 ),? @separator CHAR ( 1 ) = ‘ , ‘ ) RETURNS @splitstringstable TABLE (? [ item ] NVARCHAR ( 200 )) AS BEGIN ??? DECLARE @currentindex INT ??? DECLARE @nextindex INT ??? DECLAR
create FUNCTION [dnt_split] ( ?@splitstring NVARCHAR(4000),?@separator CHAR(1) = ‘,‘ ) RETURNS @splitstringstable TABLE ( ?[item] NVARCHAR(200) ) AS BEGIN ??? DECLARE @currentindex INT ??? DECLARE @nextindex INT ??? DECLARE @returntext NVARCHAR(200) ??? SELECT @currentindex=1 ??? WHILE(@currentindex<=datalength(@splitstring)/2) ??? BEGIN ??????? SELECT @nextindex=charindex(@separator,@splitstring,@currentindex) ??????? IF(@nextindex=0 OR @nextindex IS NULL) ??????????? SELECT @nextindex=datalength(@splitstring)/2+1 ??????? ??????? SELECT @returntext=substring(@splitstring,@currentindex,@nextindex-@currentindex) ??????? INSERT INTO @splitstringstable([item]) ??????? VALUES(@returntext) ??????? ??????? SELECT @currentindex=@nextindex+1 ??? END ??? RETURN END ? 上面版本,最多支持4000个字符,客户说选太多项目时会丢失数据,分析函数,直接把nvarchar(4000)改成Text,可以支持更长的字符串,很自信的在客户机子上运行,居然有异常,跟踪代码如果只输入 ALTER FUNCTION [dbo].[dnt_split] ( @splitstring TEXT,@separator CHAR(1) = ‘,‘ ) RETURNS @splitstringstable TABLE ( [item] VARCHAR(200) ) AS BEGIN DECLARE @currentindex INT DECLARE @nextindex INT DECLARE @returntext VARCHAR(200) SELECT @currentindex=1 WHILE(@currentindex<=datalength(@splitstring)) BEGIN SELECT @nextindex=charindex(@separator,@currentindex) IF(@nextindex=0 OR @nextindex IS NULL) SELECT @nextindex=datalength(@splitstring)+1 SELECT @returntext=substring(@splitstring,@nextindex-@currentindex) INSERT INTO @splitstringstable([item]) VALUES(@returntext) SELECT @currentindex=@nextindex+1 END RETURN END (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |