您將需要某種形式的遞歸的替換。 像一個循環
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
規範化表的生活會容易得多 –
這是實際的設計..數值只是設定的例子,但真實的數據是比較複雜的看.. –