您现在的位置是:网站首页> 编程资料编程资料
SQL里面用自定义Split()完成个性化需求_MsSql_
2023-05-26
456人已围观
简介 SQL里面用自定义Split()完成个性化需求_MsSql_
复制代码 代码如下:
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 Server:多行合并成一行,并做分组统计的两个方法_MsSql_
- 将备份的SQLServer数据库转换为SQLite数据库操作方法_MsSql_
- SQLSERVER对索引的利用及非SARG运算符认识_MsSql_
- SQLSERVER记录登录用户的登录时间(自写脚本)_MsSql_
- SQLSERVER如何查看索引缺失及DMV使用介绍_MsSql_
- 诊断SQLSERVER问题常用的日志概述及使用_MsSql_
- 自动化收集SQLSERVER诊断信息的工具选择及使用介绍_MsSql_
- SQLSERVER聚集索引和主键(Primary Key)的误区认识_MsSql_
- SQLserver删除某数据库中所有表实现思路_MsSql_
- sqlserver 各种判断是否存在(表名、函数、存储过程等)_MsSql_
