Select len(productid),productid,*
FROM dbo.produts
where Place = 'KA'
and len(productid) <> 10
order by len(productid)
此查询过滤需要更新的数据 - 我需要更新&quot; productid&#39;格式不正确 - (数据应为10个字符,采用4-2-4格式,前导0为需要的地方)(productid列为varchar(256)列) 基本上我需要将前导零添加到具有where条件的varchar列
|productid| |Correct productid value| |
---------------------------------------
|234-55-43||000234-55-43|
|76-7-89||0000076-7-89|
更新这些记录的可能解决方案是什么?
答案 0 :(得分:3)
这很简单,实际上是:
SELECT productid,
RIGHT('000000000'+productid,10) CorrectProductid
FROM dbo.YourTable
;
答案 1 :(得分:1)
如果您希望更正的格式为您提到的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 '____-__-____'