简体   繁体   中英

How to convert varchar to date format

I want to convert my field (dateVar = '08/2018') to a real date field. Actually i have only months and years, so i need to add just 01 like a day. My final result should be 2018-08-01.

CREATE TABLE dateTable (
    dateVar varchar(10)
);

insert into dateTable (dateVar)
values('08/2018'),('01/2015');

i used this to convert to date but doesnt work

SELECT CONVERT(date, dateVar, 103) FROM dateTable

You could concatenate missing 01 :

SELECT CONVERT(date, '01/'+dateVar, 103)
FROM tab

DBFiddle Demo

To avoid problems with incorrect user input you could use TRY_CONVERT . In case of conversion error it will return NULL instead.

You should use standard formats for dates:

insert into dateTable (dateVar)
    values('2018-08-01'), ('2015-01-01');

The hyphens is ISO standard and standard in most databases. It almost always works correctly in SQL Server, but the real SQL Server standard drops the hyphens -- '20180801' and '20150101' .

The table should then be declared to have a date for the column:

CREATE TABLE dateTable (
    dateVar date
);

If you need to see this in a particular format, use a computed variable:

CREATE TABLE dateTable (
    dateVar date,
    date_mmyyyy as (right(convert(varchar(10), dateVar, 103), 7))
);

Then date_mmyyyy shows the value as you would like to see it.

技巧只是将字符串转换为YYYYMMDD格式并将其强制转换。

cast(right(dateVar,4) + left(dateVar,2) + '01' as date) 

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