Replace with wildcard, in SQL

后端 未结 6 818
孤独总比滥情好
孤独总比滥情好 2020-12-19 01:46

I know MS T-SQL does not support regular expression, but I need similar functionality. Here\'s what I\'m trying to do:

I have a varchar table field which stores a b

6条回答
  •  难免孤独
    2020-12-19 02:14

    I think your best bet is going to be to use a recursive user-defined function (UDF). I've included some code here that you can use to pass in a string to achieve the results you're looking for.

    CREATE FUNCTION ufn_StripIDsFromBreadcrumb (@cIndex int, @breadcrumb varchar(max), @theString varchar(max))
    
    RETURNS varchar(max)
    
    AS
    
    BEGIN
    DECLARE @nextColon int
    DECLARE @nextSlash int
    
    SET @nextColon = CHARINDEX(':', @theString, @cIndex)
    SET @nextSlash = CHARINDEX('/', @theString, @nextColon)
    SET @breadcrumb = @breadcrumb + SUBSTRING(@theString, @nextColon + 1, @nextSlash - @nextColon)
    
    IF @nextSlash != LEN(@theString)
    
         BEGIN
         exec @breadcrumb = ufn_StripIDsFromBreadcrumb @cIndex =  @nextSlash, @breadcrumb = @breadcrumb, @theString = @theString
         END
    RETURN @breadcrumb
    END
    

    You could then execute it with:

    DECLARE @myString varchar(max)
    EXEC @myString = ufn_StripIDsFromBreadcrumb 1, '/', '/ID1:Category1/ID2:Category2/ID3:Category3/'
    PRINT @myString
    

提交回复
热议问题