Aggregate replace in SQL Server?

前端 未结 3 1889
名媛妹妹
名媛妹妹 2021-01-22 03:25

What I\'m trying to achieve is to make dynamic a series of replacements that have to be performed on a certain field. (To make things even easier, I want in fact to remove data,

3条回答
  •  不思量自难忘°
    2021-01-22 03:53

    You can setup a table variable with FromValue and ToValue and use a while loop to do the replacements.

    -- Table to replace in
    declare @T table
    (
      Value varchar(50)
    )
    
    insert into @T values
    ('first second third'),
    ('first second third')
    
    -- Table with strings to replace
    declare @Rep table
    (
      ID int identity primary key,
      FromValue varchar(50),
      ToValue varchar(50)
    )
    
    insert into @Rep values
    ('second', 'fourth'),
    ('third', 'fifth')
    
    declare @ID int
    select @ID = max(ID)
    from @Rep
    
    while @ID > 0
    begin
      update @T
      set Value = replace(Value, FromValue, ToValue)
      from @Rep
      where ID = @ID
    
      set @ID -= 1
    end
    
    select *
    from @T
    

    Result:

    Value 
    -------------------
    first fourth fifth
    first fourth fifth
    

    If you only want to query the values you can do something like this.

    ;with C as
    (
      select 0 as ID, 
             Value,
             0 as Lvl
      from @T
      union all
      select R.ID,
             cast(replace(C.Value, R.FromValue, R.ToValue) as varchar(50)),
             Lvl + 1
      from @Rep as R
        inner join C
          on C.ID + 1 = R.ID
    )
    select top 1 with ties Value
    from C
    order by Lvl desc
    

提交回复
热议问题