码迷,mamicode.com
首页 > 数据库 > 详细

SQL 分割函数

时间:2015-03-31 17:56:20      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER FUNCTION [dbo].[Split]
(
@SplitString nvarchar(4000), -- 如果要传入NText类型,下面需要相应的修改,注释行为NText下同
@Separator varchar(2) = ‘,‘-- NVarChar(2) = N‘,‘
)
RETURNS @SplitStringsTable TABLE
(
[id] int identity(1,1),
[value] varchar(8000) -- NVarChar(4000)
)
AS
BEGIN
DECLARE @CurrentIndex int;
DECLARE @NextIndex int;
DECLARE @ReturnText nvarchar(4000);-- NVarChar(4000)
SELECT @CurrentIndex=1;
WHILE(@CurrentIndex<=datalength(@SplitString)) -- DATALENGTH(@SplitString)/2
BEGIN
SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex);
IF(@NextIndex=0 OR @NextIndex IS NULL)
SELECT @NextIndex=datalength(@SplitString)+1;--DATALENGTH(@SplitString)/2

SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex);

INSERT INTO @SplitStringsTable([value])
VALUES(@ReturnText);

SELECT @CurrentIndex=@NextIndex+1;
END
RETURN;
END

 

SQL 分割函数

标签:

原文地址:http://www.cnblogs.com/lileiprc/p/4381340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!