SQL Query - Fetching Next 12 Months (MMM-YYYY Format)
DECLARE @Today DATETIME
, @nMonths TINYINT
SET @Today = GETDATE()
SET @nMonths = 12
SELECT SUBSTRING(DATENAME(MONTH, DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))), 1, 3)
+ '-' + CAST(YEAR(DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))) AS VARCHAR(4))
AS EndDateOP
FROM ( SELECT TOP ( @nMonths )n = ROW_NUMBER() OVER ( ORDER BY NAME )
FROM master.dbo.syscolumns ) n
ORDER BY 1 DESC
Output
DECLARE @Today DATETIME
, @nMonths TINYINT
SET @Today = GETDATE()
SET @nMonths = 12
SELECT SUBSTRING(DATENAME(MONTH, DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))), 1, 3)
+ '-' + CAST(YEAR(DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))) AS VARCHAR(4))
AS EndDateOP
FROM ( SELECT TOP ( @nMonths )n = ROW_NUMBER() OVER ( ORDER BY NAME )
FROM master.dbo.syscolumns ) n
ORDER BY 1 DESC
Output
Sep-2016
Oct-2016
Nov-2016
May-2017
Mar-2017
Jun-2016
Jul-2016
Jan-2017
Feb-2017
Dec-2016
Aug-2016
Apr-2017
OR
SELECT SUBSTRING(DATENAME(MONTH, DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))), 1, 3)
+ '-' + CAST(YEAR(DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))) AS VARCHAR(4))
AS EndDateOP
FROM ( SELECT TOP ( @nMonths )n = ROW_NUMBER() OVER ( ORDER BY NAME )
FROM master.dbo.syscolumns ) n
ORDER BY 1 DESC
OR
SELECT SUBSTRING(DATENAME(MONTH, DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))), 1, 3)
+ '-' + CAST(YEAR(DATEADD(dd, -1, DATEADD(month, n.n + DATEDIFF(month, 0, @Today), 0))) AS VARCHAR(4))
AS EndDateOP
FROM ( SELECT TOP ( @nMonths )n = ROW_NUMBER() OVER ( ORDER BY NAME )
FROM master.dbo.syscolumns ) n
ORDER BY 1 DESC
Wcresret0suzu1994 Megan White https://wakelet.com/wake/nvLituos_L_5R9Xm8JKSs
ReplyDeleteveratestbrev