[Solved] Get previous month in SQL when given a varchar


Try this:

DECLARE @dt VARCHAR(8) = '201501'

SELECT LEFT(CONVERT(VARCHAR(8), DATEADD(m, -1, @dt + '01'), 112), 6)

Output:

201412

Using DATEADD you can calculate the previous month. This function conveniently accepts a string as an argument. CONVERT is then used to convert the result back to yyyymmdd format.

1

solved Get previous month in SQL when given a varchar