2013-03-06 19 views
2

我有一個包含文本列的table A。 在我的存儲過程中,我有一個臨時表,包含兩列 - 舊值和新值,有多個行。 我需要使用在我的table A中的文本列中的臨時表中指定的新值來替換所有舊值的出現。SQL:使用來自另一個表的新舊值替換列中的文本值

表A中的文本字段與臨時表中的oldvalue不同,因此我無法使用聯接。文本列的值可能是「沒有任何內容」。臨時表中可能有一行oldvalue ='there'和newvalue ='here'。 最後,列值應該被替換爲'這裏什麼都沒有'。這應該適用於table A中列的所有行。

一種選擇是遍歷臨時表(不是首選)。有沒有更好/優雅/優化的方式來做到這一點?

+0

示例數據可能會有所幫助。你的意思是臨時表包含例如'(舊的,新的)(狗,狼),(棕色,黑色)',你想更新字符串「快速的棕色狐狸跳過懶惰的狗」到「快速黑狼跳過懶狗「? – 2013-03-06 13:30:28

+0

@MartinSmith - 確實如此。 – ubaid 2013-03-06 13:39:12

+0

可能重複的[用交叉引用臨時表 - tsql替換部分字符串大寫](http://stackoverflow.com/questions/13918473/replace-part-of-string-with-capitalised-equivalent-from-cross -ref-temp-table -t) – 2013-03-06 13:45:42

回答

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

表A中的文本字段與臨時表中的oldvalue不同,因此我無法使用聯接。文本列的值可能是「沒有任何內容」。臨時表中可能有一行oldvalue ='there'和newvalue ='here'。現在,輸出應該是'這裏沒有什麼'。這應該適用於表A中列的所有行。希望我有道理。 :) – ubaid 2013-03-06 13:32:12

+0

嘗試顯示一些示例數據..因爲我不明白。這會將新值與表a中的舊值相匹配 – 2013-03-06 13:34:44

+0

通過示例編輯我的評論。 – ubaid 2013-03-06 13:35:25

相關問題