Does REPLACE function in SQL Server accept input from a table for 'string_pattern' parameter?

后端 未结 5 1430
清酒与你
清酒与你 2021-01-25 08:55

I\'m still learning my ropes with SQL Server and maybe this question sounds very naive/ridiculous. Please bear with me on this. :)

I saw a function in SQL Server defined

5条回答
  •  既然无缘
    2021-01-25 09:23

    This is a hacky trick called Quirky Update

    This is slow and in most cases something one should avoid

    Some examples:

    DECLARE @tbl TABLE(SomeInt INT);
    INSERT INTO @tbl VALUES (1),(2),(3);
    
    DECLARE @SumOfInts INT=0
    SELECT @SumOfInts = @SumOfInts + SomeInt FROM @tbl;
    SELECT @SumOfInts; --SELECT SUM(SomeInt) FROM @tbl is clearly better...)
    

    String concatenation

    DECLARE @tbl2 TABLE(SomeText VARCHAR(100));
    INSERT INTO @tbl2 VALUES ('a'),('b'),('c');
    
    DECLARE @ConcatString VARCHAR(100)='';
    SELECT @ConcatString = @ConcatString + ', ' + SomeText FROM @tbl2;
    SELECT @ConcatString;
    

    Better was the usual approach with FOR XML PATH('') and STUFF(), which is a hacky workaround too. (Newer versions will bring a built-in function at last!)

    With REPLACE it works!

    This Quirky Update is the only way I know to use a table's values for a step-by-step replacement of many values you can maintain in a table dynamically:

    Look at this:

    DECLARE @ReplaceValues TABLE(this VARCHAR(100),[by] VARCHAR(100));
    INSERT INTO @ReplaceValues VALUES('$',' Dollar'),('€',' Euro'),('abbr.','abbreviations');
    
    DECLARE @SomeText VARCHAR(MAX)=
    'This text is about 100 $ or 100 € and shows how to replace abbr.!';
    
    SELECT @SomeText=REPLACE(@SomeText,this,[by]) FROM @ReplaceValues;
    
    SELECT @SomeText;
    

    The result

    --This text is about 100  Dollar or 100  Euro and shows how to replace abbreviations!
    

提交回复
热议问题