How can I convert, for example, ddmmyyyy which is a varchar(8) to date format(dd/mm/yyyy)?
I have a stored procedure which accepts a date varchar(8) parameter.
I want to convert it to date format before inserting into database. I tried to use
INSERT INTO mytable(createdDate) VALUES (CONVERT(date, CONVERT(varchar(8), @date), 106));
An error:
Conversion failed when converting date and/or time from character string.
createdDate column is type : date
ddmmyyyy
is not a valid date format. You need to first make that string into something that can be parsed as aDATE
/DATETIME
. The quickest way might be to simplySUBSTRING
the pieces into amm/dd/yyyy
format. That does convert successfully. But you have aVARCHAR(8)
. So you either need to increase that to beVARCHAR(10)
(or better yet, justCHAR(10)
), or declare a local variable to hold the altered value.For example:
EDIT: Actually, I found a slightly simpler way. I started out with this method but realized that it did not work with
ddmmyyyy
as opposed tommddyyyy
. I somehow missed that there was an appropriate date style number fordd/mm/yyyy
. So, simply adding two slashes to the incoming string and then callingCONVERT
does work, but only if you use103
as the "style". And like the first solution, it requires either changing the incoming parameter to beVARCHAR(10)
orCHAR(10)
instead ofVARCHAR(8)
, or creating a local variable to beCHAR(10)
.Conversion "styles" can be found on the MSDN page for CAST and CONVERT.