Shilpi Singh
Shilpi Singh

Reputation: 19

How to Convert String to Date in SQL Server?

I have date column in my table as string type example Feb-18. How do I change it to date type as 01-02-2018?

Upvotes: 1

Views: 196

Answers (3)

Suraj Kumar
Suraj Kumar

Reputation: 5643

You can also try the following way.

Select try_cast('01-' + 'Feb-18' as Date) as [String To Date]

Upvotes: 0

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

Use convert() with add one day :

select convert(date, '01-' + 'Feb-18')

Upvotes: 6

Gordon Linoff
Gordon Linoff

Reputation: 1269483

SQL Server is pretty good about figuring out dates. But you need a day, so:

select convert(date, '01-' + datecol)

Note: You should be very careful about storing dates as strings. I would recommend that you test the conversion to be sure it works for all values:

select datecol
from t
where try_convert(date, '01-' + datecol) is null and
      datecol is not null;

If this returns any rows, then you have bad dates in your data. Oh, it would have been better to catch these by rejecting the insert/updates in the first place. However, you might be able to figure out how to fix them.

Upvotes: 5

Related Questions