【问题标题】:SQL : Replace text value in a column using old-new values from another tableSQL:使用另一个表中的旧值替换列中的文本值
【发布时间】:2013-02-21 07:36:16
【问题描述】:

我有一个包含文本列的table A。 在我的存储过程中,我有一个临时表,其中包含两列 - 旧值和新值,有许多行。 我需要用我的table A 的文本列中的临时表中指定的新值替换所有出现的旧值。

表 A 中的文本字段与临时表中的旧值不同,因此我不能使用连接。文本列值可以是“那里什么都没有”。临时表中可能有一行 oldvalue='there' 和 newvalue='here'。 最后,列值应替换为“here is nothing here”。这应该应用于table A 中列的所有行。

一种选择是遍历临时表(不推荐)。有没有更好/优雅/优化的方式来做到这一点?

【问题讨论】:

标签: sql sql-server tsql replace query-optimization


【解决方案1】:

应该这样做。

;with r as (
  select 
    row_number() over(order by oldv) rn
    ,oldv
    ,newv
  from #replacevalues
)
,
res as (
  select 
    0 as ver
    ,txt as oldcte
    ,txt as newcte
  from tablea
  union all
  select 
    ver+1
    ,oldcte
    ,replace(newcte,oldv,newv)
  from res 
  join r 
    on r.rn=ver+1
)
update t
  set txt = res.newcte
from tablea t
join res on t.txt = res.oldcte
where res.ver = (select max(ver) from res)

【讨论】:

  • 表 A 中的文本字段与临时表中的旧值不同,所以我不能使用连接。文本列值可以是“那里什么都没有”。临时表中可能有一行 oldvalue='there' 和 newvalue='here'。现在,输出应该是“这里什么都没有”。这应该适用于表 A 中列的所有行。希望我说得通。 :)
  • 尝试显示一些示例数据..因为我不明白。这会将新值放在与表 a 中旧值匹配的位置
  • 用一个例子编辑了我的评论。
猜你喜欢
  • 2016-11-25
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多