SQL-如何使用case将varchar转换为int
我有一张这样的桌子SQL-如何使用case将varchar转换为int,sql,Sql,我有一张这样的桌子 productId Inventory -------------------- 1 1 2 Ab 3 12.5 4 6 6 2 如何选择库存为int而其他值为零,其中库存为varchar?假设这是SQL Server,则可以执行以下操作: select case when isnumeric(inventory) then cast(inv
productId Inventory
--------------------
1 1
2 Ab
3 12.5
4 6
6 2
如何选择库存为
int
而其他值为零,其中库存为varchar
?假设这是SQL Server,则可以执行以下操作:
select case when isnumeric(inventory) then
cast(inventory as INT)
else
0
end
SELECT productid,
CAST((CASE isnumeric(inventory)
WHEN 0 THEN 0
ELSE CAST(Inventory AS DECIMAL(10, 2))
END) AS INT) AS Inventory
FROM tablename
这将为您提供:
| PRODUCTID | INVENTORY |
-------------------------
| 1 | 1 |
| 2 | 0 |
| 3 | 12 |
| 4 | 6 |
| 6 | 2 |
如果希望12.5等十进制值显示为整数而不是小数,则必须执行以下操作来修剪小数位数:
select case when isNumeric(Inventory) = 1 then cast(cast(Inventory as DECIMAL(10,0)) as INT) else 0 end as Inventory_INT, productId
from PRODUCTS
使用PatIndex()
更安全。IsNumeric不是在sql server中检查数值的最佳方法,因为它也将为货币符号返回1(例如,IsNumeric(“$”)
等于1)
下面的示例不是对十进制值进行四舍五入。如果需要对值进行四舍五入,则将库存转换为十进制。使用Patindex()
函数
select productId, case patindex('%[0-9]%',inventory)
when 1 then convert(int,convert(decimal(10,2),inventory))
else 0 end inventory
from T
| PRODUCTID | INVENTORY |
-------------------------
| 1 | 1 |
| 2 | 0 |
| 3 | 12 |--NOTE
| 4 | 6 |
| 6 | 2 |
| 7 | 0 |--Extra data row added with '$'
从库存中获取四舍五入值
select productId, case patindex('%[0-9]%',inventory)
when 1 then convert(decimal,inventory)
else 0 end inventory
from T
| PRODUCTID | INVENTORY |
-------------------------
| 1 | 1 |
| 2 | 0 |
| 3 | 13 |--NOTE
| 4 | 6 |
| 6 | 2 |
| 7 | 0 |--Extra data row added with '$'
嗨,这给了我所有的十进制结果,如何在整数中转换什么整数你会分配给'ab'或12.5?嗨,谢谢你的帮助。问题解决方案如果有帮助,a+1就很好:)Isnumeric()
不能用于检查sql server中的数值。这不能解决你的问题。偶数是数字(',')=1
。嗨,是的,卡夫。谢谢为我提供解决方案没问题,你在sql server上吗?