简体   繁体   中英

SQL convert or cast a varchar to datetime

I've got a table with a column DATEDEPOT as varchar(20) .

The information inside are like this : 20020101 - I mean 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.
É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
É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'.

See http://msdn.microsoft.com/en-us/library/ms187819.aspx for more on datetime.

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.

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.

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