Find a specific substring using Transact-SQL

后端 未结 6 637
孤独总比滥情好
孤独总比滥情好 2021-01-27 06:24

I need to pull a specific substring from a string of the form:

foo=abc;bar=def;baz=ghi

For example, how would I get the value of \"bar\" from t

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 07:18

    I have a generalized solution that works for this problem:

    CREATE FUNCTION [dbo].[fn_StringBetween]
    (
        @BaseString varchar(max),
        @StringDelim1 varchar(max),
        @StringDelim2 varchar(max)
    )
    RETURNS varchar(max)
    AS
    BEGIN
        DECLARE @at1 int
        DECLARE @at2 int
        DECLARE @rtrn varchar(max)
    
        SET @at1 = CHARINDEX(@StringDelim1, @BaseString)
        IF @at1 > 0
        BEGIN
            SET @rtrn = SUBSTRING(@BaseString, @at1
             + LEN(@StringDelim1), LEN(@BaseString) - @at1)
            SET @at2 = CHARINDEX(@StringDelim2, @rtrn)
            IF @at2 > 0
                SET @rtrn = LEFT(@rtrn, @at2 - 1)
        END
    
        RETURN @rtrn
    END
    

    so if you run (just wrap your original string to be searched with ';' at beginning and end):

    PRINT dbo.fn_StringBetween(';foo=abc;bar=def;baz=ghi;', ';bar=', ';')
    

    you will get 'def' returned.

提交回复
热议问题