--循环按固定长度截取
--CJ2249301801,CJ2249300803,CJ2249301901,CJ2249302003 截取 形式301,300,301,302
CREATE FUNCTION [dbo].[FN_LOOPSUBSTRING](
@string NVARCHAR(MAX),
@spchar CHAR(1),
@strlen INT,
@eachstrEnoughLenStartIndex INT,
@eachstrEnoughLenEndIndex INT,
@eachstrNotEnoughLenStartIndex INT,
@eachstrNotEnoughLenEndIndex INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
--DECLARE @string as nvarchar(max) -- 源字符串,子串间用分隔符隔开
--DECLARE @spchar as char(1) -- 分隔符
--DECLARE @strlen INT
--DECLARE @eachstrEnoughLenStartIndex INT
--DECLARE @eachstrEnoughLenEndIndex INT
--DECLARE @eachstrNotEnoughLenStartIndex INT
--DECLARE @eachstrNotEnoughLenEndIndex INT
--SET @spchar=',' -- 分隔符
--SET @string='CJ2249301801,CJ2249300803,CJ2249301901,CJ2249302003'
--SET @strlen=12
--SET @eachstrEnoughLenStartIndex=6
--SET @eachstrEnoughLenEndIndex=3
--SET @eachstrNotEnoughLenStartIndex=1
--SET @eachstrNotEnoughLenEndIndex=3
DECLARE @startIndex as int -- 起点
DECLARE @endIndex as int -- 结束点
DECLARE @log as nvarchar(max) -- 执行记录
DECLARE @count as int -- 查找次数
-- 源字符串,起点不包含分隔符,结束包含分隔符
SET @startIndex=0 -- 0位置为初起点
SET @log=''
SET @count=1
SELECT @endIndex=CHARINDEX(@spchar,@string);-- 第1个分隔符位置为结束点
-- charindex找不到字符串时,返回0.循环成立条件是能找到分隔符
WHILE @endIndex>0
BEGIN
DECLARE @subStr as nvarchar(20) -- 子字符串
-- 根据起止点及起止点之差为长度找出子字符串
SELECT @subStr=SUBSTRING(@string,@startIndex,@endIndex-@startIndex)
-- 下一起点为当前止点加1
SET @startIndex=@endIndex+1
-- 查找下一分隔符位置,即新的止点
SET @endIndex=CHARINDEX(@spchar,@string,@startIndex);
IF LEN(@subStr)>=@strlen
BEGIN
SET @subStr=SUBSTRING(@subStr,@eachstrEnoughLenStartIndex,@eachstrEnoughLenEndIndex)
END;
ELSE
BEGIN
SET @subStr=SUBSTRING(@subStr,@eachstrNotEnoughLenStartIndex,@eachstrNotEnoughLenEndIndex)
END;
IF @count=1
BEGIN
SET @log=@log+@subStr
END;
ELSE
BEGIN
SET @log=@log+@spchar+@subStr
END;
SET @count=@count+1
END
RETURN @log
END;