服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Sql Server - SQL里面用自定义Split()完成个性化需求

SQL里面用自定义Split()完成个性化需求

2019-12-31 15:53MSSQL教程网 Sql Server

为了满足需求自定义Split()在SQL中实现,代码很整洁,感兴趣的朋友可以参考下,或许对你学习sql语句有所帮助

代码如下:


SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
CREATE function [dbo].[SplitString] 

@Input nvarchar(max), 
@Separator nvarchar(max)=',', 
@RemoveEmptyEntries bit=1 

returns @TABLE table 

[Id] int identity(1,1), 
[Value] nvarchar(max) 

as 
begin 
declare @Index int, @Entry nvarchar(max) 
set @Index = charindex(@Separator,@Input) 
while (@Index>0) 
begin 
set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) 
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') 
begin 
insert into @TABLE([Value]) Values(@Entry) 
end 
set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) 
set @Index = charindex(@Separator, @Input) 
end 
set @Entry=ltrim(rtrim(@Input)) 
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') 
begin 
insert into @TABLE([Value]) Values(@Entry) 
end 
return 
end 


函数、表都建好了,下面调用测试一下吧: 

复制代码代码如下:


declare @str1 varchar(max), @str2 varchar(max), @str3 varchar(max) 
set @str1 = '1,2,3' 
set @str2 = '1###2###3' 
set @str3 = '1###2###3###' 
select [Value] from [dbo].[SplitString](@str1, ',', 1) 
select [Value] from [dbo].[SplitString](@str2, '###', 1) 
select [Value] from [dbo].[SplitString](@str3, '###', 0) 


结果,截个图来看一下:
SQL里面用自定义Split()完成个性化需求

延伸 · 阅读

精彩推荐