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

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

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
这个方法非常实用,没有字符长度限制,分出的结果也十分正确。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值