zoukankan      html  css  js  c++  java
  • SQL按指定符号分割字符串函数

    一、SQL分割字符串,返回临时表

    方法一:

     1 create function [dbo].[f_split]
     2 (
     3     @c varchar(2000),--需要分割的字符串(例如:1,2,3,4,5    我|和|你)
     4     @split varchar(2)--分隔符(例如 ,  |  $)
     5 )
     6 returns @t table(col varchar(200))--返回表
     7 as
     8     begin
     9         while(charindex(@split,@c)<>0)
    10         begin
    11             insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))
    12             set @c = stuff(@c,1,charindex(@split,@c),'')
    13         end
    14         insert @t(col) values (@c)
    15         return
    16     end

    方法二:

     1 create function [dbo].[f_split]
     2 (
     3     @str varchar(2000),--需要分割的字符串(例如:1,2,3,4,5    我|和|你)
     4     @spliter varchar(2)--分隔符(例如 ,  |  $)
     5 )
     6 returns @tb table(ch varchar(200))--返回表
     7 as
     8     begin
     9         declare @num int,@pos int, @nextpos int
    10         set @num = 0
    11         set @pos = 1
    12         while(@pos <= LEN(@str))
    13             begin
    14             select @nextpos = CHARINDEX(@spliter, @str, @pos)
    15             if(@nextpos = 0 or @nextpos is null)
    16             select @nextpos = LEN(@str) + 1
    17             insert into @tb values(RTRIM(LTRIM(SUBSTRING(@str, @pos, @nextpos - @pos))))
    18             select @pos = @nextpos+1
    19             end
    20         return
    21     end

    二、SQL分割字符串,返回元素个数

    create function f_GetArrayLength
    (
        @str varchar(2000),--需要分割的字符串(例如:1,2,3,4,5    我|和|你)
        @split varchar(2)--分隔符(例如 ,  |  $)
    )
    returns int
    as
        begin
        declare @location int
        declare @start int
        declare @length int
        set @str=ltrim(rtrim(@str))
        set @location=charindex(@split,@str)
        set @length=1
        while @location<>0
            begin
            set @start=@location+1
            set @location=charindex(@split,@str,@start)
            set @length=@length+1
            end
        return @length
        end
  • 相关阅读:
    CommandLine
    eclipse创建java和web工程
    rabbitmq安装(ubuntu)
    vue搭建手顺
    docker配置仓库源
    spark基本概念整理
    Vue整合d3.v5.js制作--柱状图(rect)
    Vue整合d3.v5.js制作--折线图(line)
    k8s强制删除pod
    踩坑ios H5
  • 原文地址:https://www.cnblogs.com/zhipeng007/p/10777728.html
Copyright © 2011-2022 走看看