简体   繁体   English

SQL 将 varchar 转换或强制转换为日期时间

[英]SQL convert or cast a varchar to datetime

I've got a table with a column DATEDEPOT as varchar(20) .我有一个表,其中列DATEDEPOTvarchar(20)

The information inside are like this : 20020101 - I mean YYYYMMDD里面的信息是这样的: 20020101 - 我的意思是YYYYMMDD

I would like to convert this in datetime.我想在日期时间转换它。

For this, I check the answer to other post but nothing is working for me.为此,我查看了其他帖子的答案,但没有任何效果。

Here is what I tried:这是我尝试过的:

select datedepot, cast(datedepot as datetime) as test from DessinsV2

I get this message :我收到这条消息:

Msg 241, Niveau 16, État 1, Ligne 1. Msg 241, Niveau 16, État 1, Ligne 1。
Échec de la conversion de la date et/ou de l'heure à partir d'une chaîne de caractères. Échec de la Conversion de la date et/ou de l'heure à partir d'une chaîne de caractères。

I've tried this :我试过这个:

declare @Madate char(10)
SELECT @MaDate=datedepot from DessinsV2

select convert(datetime,left(@Madate,4)+substring(@Madate,5,2)+right(@Madate,2))as DATEDEPOTTEST from dessinsv2

and I get :我得到:

Msg 241, Niveau 16, État 1, Ligne 1 Msg 241, Niveau 16, État 1, Ligne 1
Échec de la conversion de la date et/ou de l'heure à partir d'une chaîne de caractères. Échec de la Conversion de la date et/ou de l'heure à partir d'une chaîne de caractères。

Does this run on your machine?这是否在您的机器上运行?

DECLARE @var as nvarchar(20)
SELECT @var = '20020101'
SELECT CONVERT(datetime, @var)

This query works for me, but not if I use a date string of the format 'DDMMYYYY'.此查询对我有用,但如果我使用格式为“DDMMYYYY”的日期字符串则不行。

See http://msdn.microsoft.com/en-us/library/ms187819.aspx for more on datetime.有关日期时间的更多信息,请参阅http://msdn.microsoft.com/en-us/library/ms187819.aspx

select '20020101' as orignal_date,
       cast('20020101' as datetime) as converted_date

This Work Fine with me Please Check.这对我来说很好用,请检查。

You must specify date input format to the convert function like :您必须为转换函数指定日期输入格式,例如:

select datedepot, convert(datetime, datedepot,112) as test from DessinsV2

see: http://msdn.microsoft.com/es-es/library/ms187928.aspx for more formats.有关更多格式,请参见: http : //msdn.microsoft.com/es-es/library/ms187928.aspx

Thanks Everybody for helping.谢谢大家帮忙。

My query was good but i made a query to 'group by' and i found some irregular contents like special caracter or special digit.我的查询很好,但我查询了“分组依据”,我发现了一些不规则的内容,如特殊字符或特殊数字。 Those information couldn't be converted.这些信息无法转换。

So i ignore the line with strange information and my query is working fine.所以我忽略了带有奇怪信息的行,我的查询工作正常。

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

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