Question

I have got date in YYYYMMDD format in Varchar. Got to change this to yyyy-mm-dd format and should add 1 to the date. Should convert back to YYYYMMDD format.

Can somebody help to achieve this.

Was it helpful?

Solution

You have to convert first. Use CONVERT because you need to tell the convert function what the format is of your dataetime varchar. Further down the article I linked to you see the different acceptable formats. Looking down that table you learn that the format YYYYMMDD is called ISO format and the third parameter of our CONVERT has therefore to be 112.

and then use the DATEADD and CONVERT back again

SELECT CONVERT(VARCHAR,DATEADD(d, 1,CONVERT(DATETIME, '20140121', 112) ),112)

For 2008 and up you can use the datatype DATE, in sqlserver 2005 only the types DATETIME and SMALLDATETIME exist.

working sqlfiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top