SQL - 如何使用case将varchar转换为int

时间:2013-02-24 06:22:12

标签: sql

我有一张这样的表

productId Inventory 
--------------------    
1            1
2            Ab
3            12.5
4            6
6            2

如何选择广告资源int,其他值为零,其中Inventoryvarchar

4 个答案:

答案 0 :(得分:3)

假设这是SQL Server,那么你可以这样做:

SELECT productid, 
  CAST((CASE isnumeric(inventory) 
          WHEN 0 THEN 0 
          ELSE CAST(Inventory AS DECIMAL(10, 2)) 
        END) AS INT) AS Inventory 
FROM tablename

SQL Fiddle Demo

这会给你:

| PRODUCTID | INVENTORY |
-------------------------
|         1 |         1 |
|         2 |         0 |
|         3 |        12 |
|         4 |         6 |
|         6 |         2 |

答案 1 :(得分: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

答案 2 :(得分:0)

select case when isnumeric(inventory) then
       cast(inventory as INT)
else
       0
end

答案 3 :(得分:0)

使用PatIndex()更安全。 IsNumeric 不是检查sql-server中数值的最佳方法,因为它也会为货币符号返回1(例如,isnumerc('$') 等于为1 )msdn

以下示例不会舍入十进制值。如果需要向上舍入值,则将库存转换为小数。 Sql-Demo使用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 '$'