prøv:
DECLARE @YourTable table (YourDate datetime, value int)
insert into @YourTable VALUES ('2011-7-12',5)
;WITH AllNumbers AS
(
SELECT 0 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number<4
)
SELECT
dateadd(month,number,DATEADD(month,DATEDIFF(month,0,YourDate),0))
FROM @YourTable y
INNER JOIN AllNumbers a ON 1=1
output:
-----------------------
2011-07-01 00:00:00.000
2011-08-01 00:00:00.000
2011-09-01 00:00:00.000
2011-10-01 00:00:00.000
2011-11-01 00:00:00.000
(5 row(s) affected)
det fungerer med flere rækker i tabellen, se her:
DECLARE @YourTable table (YourDate datetime, ValueOf int)
insert into @YourTable VALUES ('2011-7-12',5)
insert into @YourTable VALUES ('2012-4-24',6)
;WITH AllNumbers AS
(
SELECT 0 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number<4
)
SELECT
y.ValueOf
,dateadd(month,number,DATEADD(month,DATEDIFF(month,0,y.YourDate),0))
FROM @YourTable y
INNER JOIN AllNumbers a ON 1=1
ORDER BY 1,2
OUTPUT:
ValueOf
----------- -----------------------
5 2011-07-01 00:00:00.000
5 2011-08-01 00:00:00.000
5 2011-09-01 00:00:00.000
5 2011-10-01 00:00:00.000
5 2011-11-01 00:00:00.000
6 2012-04-01 00:00:00.000
6 2012-05-01 00:00:00.000
6 2012-06-01 00:00:00.000
6 2012-07-01 00:00:00.000
6 2012-08-01 00:00:00.000
(10 row(s) affected)
Jeg har heller ikke SQL Server 2008 tilgængelig, så jeg brugte datetime, hvis du har 2008, kan du bruge DATE
datatype, og du behøver ikke at nedsætte datetime, så brug denne linje:
dateadd(month,number,y.YourDate)