这是我的稍微粗糙的代码。
update P_INVENTORY_MOVEMENTS set qty = REPLACE(qty,' ','')
update P_INVENTORY_MOVEMENTS set qty = REPLACE(qty,'^','')
UPDATE P_INVENTORY_MOVEMENTS SET qty = replace(replace(qty,CHAR(13),''),CHAR(10),'')
UPDATE P_Inventory_movements SET QTY = '0.00' where isnumeric (qty)<>1
它删除空格,然后是帽子,然后是换行符和回车符,最后是剩下的任何值,将其设置为0.00
我认为这可能写得很糟糕,我想知道是否有人能看到更好的方法。最好的方法是使用更大的嵌套替换还是我接近这个错误?
答案 0 :(得分:4)
试试这种方式
;WITH cte
AS (SELECT Replace(Replace(Replace(Replace(qty, ' ', ''), '^', ''), Char(13), ''), Char(10), '') new_qty,
qty
FROM P_INVENTORY_MOVEMENTS
WHERE qty LIKE '% %'
OR qty LIKE '%^%'
OR qty LIKE '%' + Char(13) + '%'
OR qty LIKE '%' + Char(10) + '%'
OR qty LIKE '%[^0-9.]%')
UPDATE cte
SET QTY = CASE
WHEN new_qty LIKE '%[^0-9.]%' THEN '0.00' else new_qty
END
最好将datatype
QTY
更改为Numeric
以避免日后插入错误数据
答案 1 :(得分:2)
在CROSS APPLY中计算替换并使用CASE更新
UPDATE P_Inventory_movements
CROSS APPLY (SELECT qtyr = REPLACE(REPLACE(REPLACE(REPLACE(qty
,' ',''),CHAR(13),''),CHAR(10),''),'^','')
) x
SET QTY = CASE isnumeric(qtyr) WHEN 1 THEN qtyr ELSE '0.00' END
答案 2 :(得分:1)
您可以嵌套替换语句,只使用2个更新语句而不是4:
UPDATE P_Inventory_movements
SET QTY = REPLACE(
REPLACE(
REPLACE(
REPLACE(qty,' ','')
,CHAR(13),'')
,CHAR(10),'')
,'^','')
UPDATE P_Inventory_movements
SET QTY = '0.00'
WHERE isnumeric (qty)<>1
答案 3 :(得分:1)
try_cast()
和try_parse()
decimal(9,2)
qty
,尽管有任何格式问题然后我会用它来尝试处理脏数据:
update p_inventory_movements set
qty = replace(replace(replace(replace(
qty
,char(13),'')
,char(10),'')
,' ','')
,'^','')
where qty like '%[^0-9.-]%';
update p_inventory_movements set
qty = coalesce(
try_parse(updqty as decimal(9,2))
,try_parse(updqty as float)
,try_parse(updqty as money))
,'0.00'
)
where try_cast(qty as decimal(9,2)) is null;
使用不同的功能测试各种错误输入:http://rextester.com/KHNE65079