简体   繁体   中英

SQL convert\cast nvarchar to int

I have a lot of '1.0' values of type nvarchar(max). I would like to convert\cast them to int but below queries:

  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.

How to convert nvarchar '1.0' to int?

Set the value to an appropriate format first:

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

Then do the alter table .

Here is a db<>fiddle using SQL Server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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