Reputation: 19
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
Reputation: 5643
You can also try the following way.
Select try_cast('01-' + 'Feb-18' as Date) as [String To Date]
Upvotes: 0
Reputation: 50163
Use convert()
with add one day :
select convert(date, '01-' + 'Feb-18')
Upvotes: 6
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
/update
s in the first place. However, you might be able to figure out how to fix them.
Upvotes: 5