このようなテーブルがあります
productId Inventory
--------------------
1 1
2 Ab
3 12.5
4 6
6 2
在庫を選択する方法int
と他の値はゼロです。どこInventory
ですかvarchar
?
このようなテーブルがあります
productId Inventory
--------------------
1 1
2 Ab
3 12.5
4 6
6 2
在庫を選択する方法int
と他の値はゼロです。どこInventory
ですかvarchar
?
これがSQLServerであるとすると、次のことができます。
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 のような 10 進数値を 10 進数ではなく int として出力する場合は、次のようにして小数点以下を切り捨てる必要があります。
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
select case when isnumeric(inventory) then
cast(inventory as INT)
else
0
end
より安全に使用できますPatIndex()
。IsNumericは、通貨記号 (例: 1 にisnumerc('$')
等しい) msdnに対しても 1 を返すため、sql-server で数値をチェックする最良の方法ではありません。
次の例は、10 進数値を切り上げていません。値を切り上げる必要がある場合は、在庫を小数に変換します。関数を使用したSql-DemoPatindex()
。
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 '$'