首页 > 代码库 > SQL分隔字符串

SQL分隔字符串

创建函数:

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

使用方式:

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

测试语句:

IF object_id(N[dbo].[split]) IS NOT NULL --检查函数【[dbo].[split]】是否存在BEGIN    DROP FUNCTION [dbo].[split] --删除函数ENDGOCREATE FUNCTION[dbo].[split](@str NVARCHAR(max),@spliter NVARCHAR(10))--@str:目标字符串--@spliter:分隔符RETURNS @tb TABLE(ch NVARCHAR(max))ASBEGINDECLARE @Num INT,@Pos INT, @NextPos INTSET @Num = 0SET @Pos = 1WHILE(@Pos <= LEN(@str))BEGINSELECT @NextPos = CHARINDEX(@spliter, @str, @Pos)IF (@NextPos = 0 OR @NextPos IS NULL)SELECT @NextPos = LEN(@str) + 1INSERT INTO @tb VALUES(RTRIM(LTRIM(SUBSTRING(@str, @Pos, @NextPos - @Pos))))SELECT @Pos = @NextPos+1ENDRETURNENDGOSELECT * FROM dbo.split(1,2,3,4,,)DROP FUNCTION [dbo].[split]
GO

说明:

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

 

SQL分隔字符串