Regex pattern inside SQL Replace function?

前端 未结 10 1326
梦谈多话
梦谈多话 2020-11-22 12:42
SELECT REPLACE(\'100.00 GB\', \'%^(^-?\\d*\\.{0,1}\\d+$)%\', \'\');

I want to replace any markup between two

10条回答
  •  醉酒成梦
    2020-11-22 13:03

    I stumbled across this post looking for something else but thought I'd mention a solution I use which is far more efficient - and really should be the default implementation of any function when used with a set based query - which is to use a cross applied table function. Seems the topic is still active so hopefully this is useful to someone.

    Example runtime on a few of the answers so far based on running recursive set based queries or scalar function, based on 1m rows test set removing the chars from a random newid, ranges from 34s to 2m05s for the WHILE loop examples and from 1m3s to {forever} for the function examples.

    Using a table function with cross apply achieves the same goal in 10s. You may need to adjust it to suit your needs such as the max length it handles.

    Function:

    CREATE FUNCTION [dbo].[RemoveChars](@InputUnit VARCHAR(40))
    RETURNS TABLE
    AS
    RETURN
        (
            WITH Numbers_prep(Number) AS
                (
                    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                )
            ,Numbers(Number) AS
                (
                    SELECT TOP (ISNULL(LEN(@InputUnit),0))
                        row_number() OVER (ORDER BY (SELECT NULL))
                    FROM Numbers_prep a
                        CROSS JOIN Numbers_prep b
                )
            SELECT
                OutputUnit
            FROM
                (
                    SELECT
                        substring(@InputUnit,Number,1)
                    FROM  Numbers
                    WHERE substring(@InputUnit,Number,1) like '%[0-9]%'
                    ORDER BY Number
                    FOR XML PATH('')
                ) Sub(OutputUnit)
        )
    

    Usage:

    UPDATE t
    SET column = o.OutputUnit
    FROM ##t t
    CROSS APPLY [dbo].[RemoveChars](t.column) o
    

提交回复
热议问题