简体   繁体   中英

T-SQL failed converting varchar to int

I need to add days to date

select Name, Surname, Days, getdate(), 
CONVERT(VARCHAR(11),DATEADD(s,CONVERT(INT, Days) ), getdate()),101 )
from myTAble

but i get error

Conversion failed when converting the varchar value '20' to data type int.

any idea?

Brackets mixed up:

select Name, Surname, Days, getdate(), 
CONVERT(VARCHAR(11),DATEADD(s,CONVERT(INT, days), getdate()),101) 
from myTAble

First your parentesis are incorrect but that's not likely the issue here. I created a verifiable example:

create table MyTable
(
 Name varchar(100)
,Surname varchar(100)
,[Days] varchar(100)
)

GO

insert into MyTable(Name,Surname,[Days])
values ('John', 'Doo', '20')
,('Stack', 'Overflow', char(178) + char(176))
GO

And now your query (with correct parentesis)

select Name, Surname, Days, getdate(), 
CONVERT(VARCHAR(11),DATEADD(s,CONVERT(INT, Days ), getdate()),101 )
from myTAble

and I managed to reproduce your problem (somewhat)

Conversion failed when converting the varchar value '²°' to data type int.

The issue here is you got a 20 is not the correct caracteres, maybe you got a collation problem .

In the example above I used a real problem I got a time ago. In the app is shows 20 but in reallity in the database we got non standart caracteres.

In the example below some special caractres can look like numeric ones

--° #176 ~ 0   --¹ #185 ~ 1   --² #178 ~ 2   --³ #179 ~ 3    
select char(178) + char(176)

You can try to check if the data is numeric

select *, isnumeric([Days]) from MyTable

In my case we sanitized the data.

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