Using another article on StackOverflow (How to split date ranges based on months in SQL Server 2005) I have run a SELECT
statement which splits up a date range by month and returns 2 columns (DateFrom, DateTo
) in SQL.
DECLARE @SDate DATE = '2012/08/01'
DECLARE @EDate DATE = '2013/09/01'
SELECT
DATEADD(MONTH, n.Number, @SDate) as DateFrom,
DATEADD(day, -1, DATEADD(MONTH, n.Number, DATEADD(YEAR,-1,@EDate))) as DateTo
FROM
master.dbo.spt_values n
WHERE
n.Number < DATEDIFF(MONTH, @SDate, @EDate)
AND n.Type = 'P'
I now need to add each of the returned rows into a string separating the columns by |
(Dateto|Datefrom
) and each row by ,
.
For example if your run the code above the result would be (just for this example im only using the first 4 rows but I need all of them in one string):
R | Date From | Date To
1 | 2012-08-01 | 2012-08-31
2 | 2012-09-01 | 2012-09-30
3 | 2012-10-01 | 2012-10-30
4 | 2012-11-01 | 2012-11-30
Code:
DECLARE @stralldates VarChar(MAX)
/* SET @stralldates = INSERTCODE */
PRINT @stralldates
What I need PRINT to return:
2012-08-01|2012-08-31,2012-10-01|2012-10-30,2012-10-01|2012-10-30,2012-11-01|2012-11-30
I have tried several suggestions from other similar questions on StackOverflow (such as CONCAT
) with no success.
Any help or suggestions would be appreciated.