2016-12-08 7 views
0

我得到了包含數據的一千個字符串以及標有'@xx'的id。如果字符串有'|'它表明有一個ID的數據更多。更換SQL中字符串的一部分

如何找到並替換包含特定ID的所有ID?如果我想換@ 1〜@ 24我不想@ 11改爲@ 241

一些exampels 預計輸出

[email protected] -> [email protected] 
[email protected] -> [email protected] 
[email protected]|[email protected]|[email protected] -> [email protected]|[email protected]|[email protected] 

更換(列, '@ 1' ,'@ 24')將不起作用,因爲@ 11將被更改爲@ 241。所以我需要知道它是否是字符串的結尾,或者是否以'|'結尾

+0

顯示您的預期輸出 – TheGameiswar

+0

我的編輯與預期的輸出 – thatsIT

回答

2

快速和骯髒,但你可能只是這樣做:

-- Update the end bits 
UPDATE table 
SET field = LEFT('field', LEN('field') -2) + '@24' 
WHERE field LIKE '%@1'; 

-- Update the in between bits 
UPDATE table 
SET field = REPLACE(field, '@1|', '@24|') 
WHERE field LIKE '%@1|%'; -- This where statement is optional due to the nature of the REPLACE. 

否則,你就必須尋找到REGEX神奇的世界。如果這是你想要跑不止一次的事情,我一定會考慮這一點。如果這只是一次性修理,嗯。今天是星期四,我會把它稱爲一個有效的藉口。

1

試試這個

declare @t table(col varchar(100)) 
insert into @t 
select '[email protected]' union all 
select '[email protected]' union all 
select '[email protected]|[email protected]|[email protected]' 


select col,case when new_col like '%|' then 
       substring(new_col,1,len(new_col)-1) 
      else 
       new_col end as new_col 
from 
(
select col, 
case when col+'|' like '%@1|%' then 
Replace(col+'|', '@1|', '@24|') else col end as new_col 
from @t 
) as t 

結果

col           new_col 
--------------------------------------------- ------------ 
[email protected]         [email protected] 
[email protected]         [email protected] 
[email protected]|[email protected]|[email protected] [email protected]|[email protected]|[email protected] 
+1

有多個'|'分隔的部分,每個都有自己的'@ xx'值?還是在您回答後添加了編輯? – 3N1GM4

+0

不,它沒有被編輯 – thatsIT

+0

當一箇中間包含'@ 1 |'時會發生什麼?這不會導致在中間剝離「|」嗎? – Jens