简体   繁体   English

T-SQL无法将varchar转换为int

[英]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. 将varchar值“²°”转换为数据类型int时,转换失败。

The issue here is you got a 20 is not the correct caracteres, maybe you got a collation problem . 这里的问题是您得到的20字符不正确,也许您遇到了整理问题

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. 在应用程序中显示20但实际上数据库中没有非标准的角色。

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. 就我而言,我们对数据进行了消毒。

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

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