zoukankan      html  css  js  c++  java
  • 字符串分割函数

    -- ================================================
    --
    Template generated from Template Explorer using:
    --
    Create Multi-Statement Function (New Menu).SQL
    --
    --
    Use the Specify Values for Template Parameters
    --
    command (Ctrl-Shift-M) to fill in the parameter
    --
    values below.
    --
    --
    This block of comments will not be included in
    --
    the definition of the function.
    --
    ================================================
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    --
    Author:
    --
    Create date: 2011-11-22
    --
    Description: 字符串分割函数
    --
    @Input:要进行分割的字符串
    --
    @Separator:分隔符
    --
    @RemoveEmptyEntries:是否移除空格
    --
    =============================================
    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
    GO

    使用方法:

    SELECT  *
    FROM [dbo].[SplitString]('1,2,3', ',', 1)



  • 相关阅读:
    洛谷1280 尼克的任务
    洛谷1140 相似基因
    洛谷1133 教主的花园
    洛谷1130 红牌
    洛谷1122 最大子树和
    洛谷1103 书本整理
    洛谷1077 摆花
    【数学】数学知识习题小结(模板)
    python中的深拷贝和浅拷贝(面试题二)
    python中的深拷贝和浅拷贝(面试题)
  • 原文地址:https://www.cnblogs.com/supperwu/p/2258479.html
Copyright © 2011-2022 走看看