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来保存排序等等。

  • 相关阅读:
    spsss基本统计分析操作攻略
    MATLAB读取Excel表格数据和处理数据
    MATLAB 雷达图画图函数
    spss新手教程
    MATLAB绘制饼状图
    高斯消元法解线性方程组(C++实现)
    Java和matlab混合编程
    Matlab与Java混合编程的教程
    两组数据的相关性分析
    vs2013+QT5环境
  • 原文地址:https://www.cnblogs.com/jerrylucky/p/4081054.html
Copyright © 2011-2022 走看看