2017-01-10 49 views
0

如何從SQL中的第二個表的列表中更新/替換第一個表的值。遺憾即時使用更換不太好()SQL從值鹼尤其更換來自不同表如何從另一個表列中替換表中的字符串

第一表的

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

二表

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

規範化表的生活會容易得多 –

+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 
0

只需使用下面通過交叉連接select語句UPDATE並享受它! ;)

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