如何从另一个表列替换表的字符串

时间:2017-01-10 07:02:27

标签: sql sql-server

如何从SQL中第二个表的列表中更新/替换第一个表的值。对不起我使用 replace()的SQL特别是从不同的表中替换值base

第一张表。

ID | Value
======================
1 | Fruits[Apple]
2 | Fruits[Apple,Mango]
3 | Apple[Red,Green]

第二张表

Search | Replace
=========================
Apple  | Orange
Green  | Yellow

2 个答案:

答案 0 :(得分:0)

您需要某种递归替换。 类似循环的东西

declare @t1 table (ID int, Value varchar(max))
declare @t2 table (Search  varchar(max), ReplaceWith varchar(max))
insert @t1 values (1, 'Fruits[Apple]'),(2, 'Fruits[Apple,Mango]'), (3, 'Apple[Red,Green]')
insert @t2 values ('Apple', 'Orange'),('Green', 'Yellow')

--loop nth times for rows that have more than one match
while exists(select top 1 * from @t1 inner join @t2 on charindex(Search, Value ) > 0)
begin 
    update @t1
    set Value = replace(Value, Search, ReplaceWith)
    from @t2
    inner join @t1 on charindex(Search, Value ) > 0
end

select * from @t1

结果

ID    Value
----- -----------------------
1     Fruits[Orange]
2     Fruits[Orange,Mango]
3     Orange[Red,Yellow]

或者,您可以使用递归CTE

;with CTE(ID, Value, rec_count)
as (
    select distinct ID, Value, 1 as rec_count  from @t1 inner join @t2 on charindex(Search, Value ) > 0
    union all
    select ID, Value = replace(Value, Search, ReplaceWith), rec_count +1
    from CTE
    inner join @t2 on charindex(Search, Value ) > 0
)
update @t1 
set Value= replaced.Value 
from @t1 t
inner join 
( select distinct ID, Value 
  from CTE c 
  where rec_count > 1 
  and rec_count = (select max(rec_count) from CTE where ID = c.ID) ) replaced on replaced.ID = t.ID

答案 1 :(得分:0)

只需通过交叉加入的select语句使用UPDATE,然后享受吧! ;)

UPDATE  tFirst
SET     Value = REPLACE(tFirst.Value, tSecond.Search, tSecond.Replace)
FROM
    [First]             tFirst
    CROSS JOIN [Second] tSecond