简体   繁体   English

SQL 将 nvarchar 转换为 int

[英]SQL convert\cast nvarchar to int

I have a lot of '1.0' values of type nvarchar(max).我有很多 nvarchar(max) 类型的“1.0”值。 I would like to convert\cast them to int but below queries:我想将它们转换为 int 但以下查询:

  SELECT CONVERT(int, Quantity)
  FROM MyTable

or或者

 SELECT CAST(Quantity as int)
  FROM MyTable

or或者

 ALTER TABLE MyTable
  ALTER COLUMN [Quantity] int;

returns error message: Conversion failed when converting the nvarchar value '1.0' to data type int.返回错误消息:将 nvarchar 值 '1.0' 转换为数据类型 int 时转换失败。

How to convert nvarchar '1.0' to int?如何将 nvarchar '1.0' 转换为 int?

Set the value to an appropriate format first:首先将值设置为适当的格式:

update mytable
    set quantity = convert(decimal, quantity)
    where quantity like '%.%';

Then do the alter table .然后做alter table

Here is a db<>fiddle using SQL Server. 是一个使用 SQL 服务器的 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM