简体   繁体   English

TSQL:从字符串转换日期和/或时间时转换失败

[英]TSQL : Conversion failed when converting date and/or time from character string

I had a query that was working but after importing again one table I see the following problem when converting a Varchar into DateTime.我有一个正在运行的查询,但在再次导入一张表后,我在将 Varchar 转换为 DateTime 时看到以下问题。

I have the following problem when running the following query:运行以下查询时出现以下问题:

select FORMAT(convert (datetime,date)  ,   'ddMMyyyy')  from  kat.[dbo].[myTable]

If I try the following I see the same problem:如果我尝试以下操作,我会看到同样的问题:

SELECT convert(datetime, date, 126) from kat.[dbo].[myTable]

The dates that I have in the main table follow the same format:我在主表中的日期遵循相同的格式:

2017-09-01

EDit with Data Screenshot for the Format:使用格式的数据屏幕截图进行编辑:

日期格式

MAny thanks in advance,非常感谢,

Kat

The dates that I have in the main table follow the same format:我在主表中的日期遵循相同的格式:

 2017-09-01

There are some stings in your table that have different format.您的表中有一些具有不同格式的刺。

Try to catch them with this code:尝试使用以下代码捕获它们:

select *
from kat.[dbo].[myTable]
where dt not like '[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]';

In future, don't store datetime values as strings, use datetime / date .将来,不要将日期时间值存储为字符串,而是使用datetime / date

UPDATE更新

So it's not true that your strings are like '2017-09-01' Here is my example with your date:因此,您的字符串类似于'2017-09-01'是不正确的,这是我的日期示例:

declare @t table (dt varchar(20));
insert into @t values ('2017-09-01');

select *
from @t
where dt not like '[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]';

My code returns no rows because '2017-09-01' reflects the format you inicated, and if it returns all rows in your case, the format is different.我的代码不返回任何行,因为'2017-09-01'反映了您指定的格式,如果它返回您的案例中的所有行,则格式不同。

I actually think strings cannot be converted directly to dates (at least not when you use CAST)... Why not convert the string to an int first?我实际上认为字符串不能直接转换为日期(至少当您使用 CAST 时不能)......为什么不先将字符串转换为 int?

Assuming your column is named [Date], I would stick with:假设您的专栏名为 [Date],我会坚持:

SELECT
cast(DATEADD(DAY, cast([Date] as int), -2) as date) as [Date]
FROM kat.[dbo].[myTable]

If you have a different column name, here is the template:如果您有不同的列名,这里是模板:

SELECT
cast(DATEADD(DAY, cast([MyColumnName] as int), -2) as date) as [MyColumnName]
FROM kat.[dbo].[myTable]

Alternatively, I've also updated your code using CONVERT (which honestly I rarely every use so it could be wrong)或者,我还使用 CONVERT 更新了您的代码(老实说,我很少每次都使用它,所以它可能是错误的)

SELECT convert(datetime, convert(int, [Date]), 126) from kat.[dbo].[myTable]

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

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