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)列),基本上,我需要向有条件的varchar列添加前导零。
|productid| |Correct productid value| |
---------------------------------------
|234-55-43||000234-55-43|
|76-7-89||0000076-7-89|更新这些记录的可能解决办法是什么?
发布于 2017-04-25 20:02:11
如果您希望更正的格式采用您提到的4-2-4格式:
使用parsename()解析字符串的片段,使用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 '____-__-____'发布于 2017-04-25 19:51:18
其实这很简单:
SELECT productid,
RIGHT('000000000'+productid,10) CorrectProductid
FROM dbo.YourTable
;https://stackoverflow.com/questions/43619723
复制相似问题