zoukankan      html  css  js  c++  java
  • 写自己需要的SQL function

    在SQL中如何写一个SplitStringFunction,话不多说,上代码:

     1 SET ANSI_NULLS ON
     2 GO
     3 SET QUOTED_IDENTIFIER ON
     4 GO
     5 
     6 CREATE function [dbo].[SplitString]
     7 (
     8     @Input nvarchar(max),    --要分割的字符串
        @Separator nvarchar(max)=',', --分隔符,可以是一个字符也可以是多个字符 9 @RemoveEmptyEntries bit=1 ) --是否移除空字符串 10 returns @TABLE table --返回一个存放已经分割好的字符串的table 11 ( 12 [Id] int identity(1,1), 13 [Value] nvarchar(max) 14 ) 15 as 16 begin 17 declare @Index int, @Entry nvarchar(max) 18 set @Index = charindex(@Separator,@Input) 19 20 while (@Index>0) 21 begin 22 set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) 23 24 if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') 25 begin 26 insert into @TABLE([Value]) Values(@Entry) 27 end 28 29 set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) 30 set @Index = charindex(@Separator, @Input) 31 end 32 33 set @Entry=ltrim(rtrim(@Input)) 34 if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') 35 begin 36 insert into @TABLE([Value]) Values(@Entry) 37 end 38 39 return 40 end

    function和table都准备好,接下来测试:

    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)

    结果:

    里面还有个自增的[Id]字段哦,在某些情况下有可能会用上的,例如根据Id来保存排序等等。

  • 相关阅读:
    java 14 -7 Date
    java 14 -6 BigInteger和BigDecimal
    java 14 -5 System类
    java14-4 Pattern和Matcher类的使用
    java 14-3 正则表达式的分割
    转:StringBuilder与StringBuffer的区别(转)
    kafka之config/server.properties配置参数说明
    Kafka内核理解:消息的收集/消费机制
    kafka删除topic及其相关数据
    kafka使用问题解决
  • 原文地址:https://www.cnblogs.com/jerrylucky/p/4081054.html
Copyright © 2011-2022 走看看