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

SQL分隔字符串

时间:2016-12-07 18:20:05      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:code   sub   nvarchar   begin   var   int   分隔符   insert   测试   

创建函数:

CREATE FUNCTION[dbo].[split](@str NVARCHAR(max),@spliter NVARCHAR(10))
--@str:目标字符串
--@spliter:分隔符
RETURNS @tb TABLE(ch NVARCHAR(max))
AS
BEGIN
DECLARE @Num INT,@Pos INT, @NextPos INT
SET @Num = 0
SET @Pos = 1
WHILE(@Pos <= LEN(@str))
BEGIN
SELECT @NextPos = CHARINDEX(@spliter, @str, @Pos)
IF (@NextPos = 0 OR @NextPos IS NULL)
SELECT @NextPos = LEN(@str) + 1
INSERT INTO @tb VALUES(RTRIM(LTRIM(SUBSTRING(@str, @Pos, @NextPos - @Pos))))
SELECT @Pos = @NextPos+1
END
RETURN
END
GO

使用方式:

SELECT * FROM dbo.split(1,2,3,4,,) --注:多行单列的数据表

测试语句:

IF object_id(N[dbo].[split]) IS NOT NULL --检查函数【[dbo].[split]】是否存在
BEGIN
    DROP FUNCTION [dbo].[split] --删除函数
END
GO


CREATE FUNCTION[dbo].[split](@str NVARCHAR(max),@spliter NVARCHAR(10))
--@str:目标字符串
--@spliter:分隔符
RETURNS @tb TABLE(ch NVARCHAR(max))
AS
BEGIN
DECLARE @Num INT,@Pos INT, @NextPos INT
SET @Num = 0
SET @Pos = 1
WHILE(@Pos <= LEN(@str))
BEGIN
SELECT @NextPos = CHARINDEX(@spliter, @str, @Pos)
IF (@NextPos = 0 OR @NextPos IS NULL)
SELECT @NextPos = LEN(@str) + 1
INSERT INTO @tb VALUES(RTRIM(LTRIM(SUBSTRING(@str, @Pos, @NextPos - @Pos))))
SELECT @Pos = @NextPos+1
END
RETURN
END
GO

SELECT * FROM dbo.split(1,2,3,4,,)

DROP FUNCTION [dbo].[split]
GO

说明:

  1、仅支持文本字符串分隔!!!

 

SQL分隔字符串

标签:code   sub   nvarchar   begin   var   int   分隔符   insert   测试   

原文地址:http://www.cnblogs.com/jschar/p/6142177.html

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