Conversion failed when converting the nvarchar value to data type int - Error Message

纵饮孤独 提交于 2021-02-19 09:13:22

问题


My Query

Select * from MyTable

The table consists 300k rows. It runs for 200k+ rows and this error pops up.

How to handle this to get the full data?

Does MyTable have any computed columns?

Table consists of a computed column with the name IsExceeds which is given below for your reference.

This is the computed column formula:

(CONVERT([int],[Pro_PCT])-CONVERT([int],replace([Max_Off],'%','')))

Field Definitions:

[Pro_PCT] [nvarchar](50) NULL,
[Max_Off] [nvarchar](50) NULL,
[IsExceeds]  AS (CONVERT([int],[Pro_PCT])-CONVERT([int],replace([Max_Off],'%','')))

回答1:


Kindly convert in float then convert into int.

declare @n nvarchar(20)
set @n='11.11'

if (isnumeric(@n)=0)
 SELECT 0
   else 
      SELECT CAST(CONVERT(float, @n) as int) AS n



回答2:


Why are you storing amounts as strings? That is the fundamental problem.

So, I would suggest fixing your data. Something like this:

update mytable
    set max_off = replace(max_off, '%');

alter table mytable alter pro_pct numeric(10, 4);
alter table mytable alter max_off numeric(10, 4);

(Without sample data or an example of the data I am just guessing on a reasonable type.)

Then, you can define IsExceeds as:

(Pro_PCT - Max_Off)

Voila! No problems.




回答3:


Based on the formula - either Pro_PCT or Max_Off contains the value 11.11 (well, with an extra % for Max_Off. Perhaps they also contain other values that can't be converted to int.

Here's what you can do to find all the rows that will cause this problem:

Select * 
from MyTable
where try_cast(Pro_PCT as int) is null
or try_cast(replace([Max_Off],'%','') as int) is null

After you've found them, you can either fix the values or change the calculation of the computed column to use try_cast or try_convert instead of convert.




回答4:


Check the bad data with

select  * from MyTable where isnumeric(  Max_Off ) = 0 


来源:https://stackoverflow.com/questions/55157257/conversion-failed-when-converting-the-nvarchar-value-to-data-type-int-error-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!