您的位置:首页 > 数据库

SQL_符号分割字符串的使用提取(针对任意长度)

2015-06-29 19:05 330 查看
题记——由于之前写的一个关于字符串分割的存储过程对于字符串的长度有限制,导致最终分割出来的字符有截断,失去数据原本的意义。在此又附上另一种对字符串的分割方式。这次采用函数来写,以方便以后都是用这个函数来处理相应的操作。

SQL 编写函数如下:

USE [SooilSemanticsDB_ImportData]
GO
/****** Object:  UserDefinedFunction [dbo].[SplitString]    Script Date: 2015/6/29 19:07:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create function [dbo].[SplitString]
(
@Input nvarchar(max), --input string to be separated
@Separator nvarchar(max)=',', --a string that delimit the substrings in the input string
@RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string
)
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
这里数据库中有一张如下的表:



采用如下的SQL语句调用函数,分割用逗号分割的字符串。
select t1.FormalTerm,t2.Value
from [dbo].[DR_BO Well] t1
outer apply [dbo].[SplitString](t1.Alias,',',1) t2




这个方法非常实用,没有字符长度限制,分出的结果也十分正确。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: