您将需要某种形式的递归的替换。 像一个循环
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
规范化表的生活会容易得多 –
这是实际的设计..数值只是设定的例子,但真实的数据是比较复杂的看.. –