[英]How do I replace strings of a table from another table column
How do I update/replace the value of the first table from the list of my second table in SQL. 如何在SQL中第二个表的列表中更新/替换第一个表的值。 Sorry im not so good in using
replace() of SQL especially replacing from values base from different table
抱歉,我在使用SQL的replace()时不太好,特别是从不同表的值基中进行
替换
First table. 第一张桌子。
ID | Value
======================
1 | Fruits[Apple]
2 | Fruits[Apple,Mango]
3 | Apple[Red,Green]
Second table 第二张桌子
Search | Replace
=========================
Apple | Orange
Green | Yellow
You will need some kind of recursive replace. 您将需要某种递归替换。 something like a loop
像一个循环
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
results 结果
ID Value
----- -----------------------
1 Fruits[Orange]
2 Fruits[Orange,Mango]
3 Orange[Red,Yellow]
Alternatively, you could use recursive CTE 或者,您可以使用递归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
Simply use following UPDATE
by cross-joined select statement and enjoy it! 只需通过交叉联接的select语句使用以下
UPDATE
享受它! ;) ;)
UPDATE tFirst
SET Value = REPLACE(tFirst.Value, tSecond.Search, tSecond.Replace)
FROM
[First] tFirst
CROSS JOIN [Second] tSecond
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.