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

に先行ゼロを追加します先頭の0を必要とする4-2-4形式で10文字にする)(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フォーマットになるように補正フォーマットを望んでいた場合文字列、right()を追加して'0'を追加します。

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

これは実際には、非常に簡単です:

はの部分を解析するparsename()を使用した:

SELECT productid, 
     RIGHT('000000000'+productid,10) CorrectProductid 
FROM dbo.YourTable 
; 
関連する問題