2017-04-25 52 views
3
Select len(productid),productid,* 
FROM dbo.produts 
    where Place = 'KA' 
    and len(productid) <> 10 
    order by len(productid) 

這個查詢過濾器需要更新 數據 - 我需要更新「的productid」是不正確的格式 數據 - (數據應是10個字符,以4-2-4格式,並且在需要它們的前導0處)(productid列是一個varchar(256)列) 基本上我需要將前導零添加到具有where條件的varchar列添加前導零到VARCHAR列

|productid| |Correct productid value| | 
--------------------------------------- 
|234-55-43||000234-55-43| 

|76-7-89||0000076-7-89| 

更新這些記錄的可能解決方案是什麼?

回答

1

如果你想修正的格式是在你提到的4-2-4格式:

使用parsename()解析出的碎片字符串和right()添加額外'0' s。

select 
    col 
    , Corrected = right('0000'+parsename(replace(col,'-','.'),3),4) 
    + '-' + right('00'+parsename(replace(col,'-','.'),2),2) 
    + '-' + right('0000'+parsename(replace(col,'-','.'),1),4) 
from t 
where col not like '____-__-____' 

rextester演示:http://rextester.com/OXM28014

回報:

+-----------+--------------+ 
| col | Corrected | 
+-----------+--------------+ 
| 234-55-43 | 0234-55-0043 | 
| 76-7-89 | 0076-07-0089 | 
+-----------+--------------+ 

作爲更新:

update t 
    set col = right('0000'+parsename(replace(col,'-','.'),3),4) 
      + '-' + right('00'+parsename(replace(col,'-','.'),2),2) 
      + '-' + right('0000'+parsename(replace(col,'-','.'),1),4) 
where col not like '____-__-____' 
3

這是非常簡單的,實際上是:

SELECT productid, 
     RIGHT('000000000'+productid,10) CorrectProductid 
FROM dbo.YourTable 
;