so I've been working on a dynamic pivot script and I've almost got it to work, but I'm having issues with declared variables. Here's my code:
DECLARE @start_date DATE
DECLARE @end_date DATE
SET @start_date = CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-7,'17530101') AS DATE)
SET @end_date = CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-1,'17530101') AS DATE)
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(TicketDate) + ','
FROM
(SELECT DISTINCT TOP 14 ad.TicketDate
FROM AttendDet ad
WHERE CAST(ad.TicketDate AS DATE) BETWEEN @start_date AND @end_date
AND ad.EmplCode IS NOT NULL
ORDER BY ad.TicketDate) as dates
SELECT @cols = SUBSTRING(@cols, 0, LEN(@cols))
SET @query =
'SELECT * FROM
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CAST(ad.TicketDate AS DATE) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> 9999
AND CAST(ad.TicketDate AS DATE) BETWEEN (' + @start_date + ') AND (' + @end_date + ')
) basedata
PIVOT
(
SUM(TotalHrs) FOR TicketDate IN (' + @cols + ')
) piv'
EXECUTE(@query)
The line that is causing an error is this one:
AND CAST(ad.TicketDate AS DATE) BETWEEN (' + @start_date + ') AND (' + @end_date + ')
The error I get is: "The data types varchar and date are incompatible in the add operator." I tried changing the data types to VARCHAR, but that didn't work, when I do that I get this error: Conversion failed when converting date and/or time from character string.
I know I'm in the right direction, because if I hardcode that line manually, for example:
AND CAST(ad.TicketDate AS DATE) BETWEEN ''10/22/18'' AND ''10/28/18''
It works perfectly as expected, but I obviously don't want to do that, as it would defeat the entire purpose of the script. The whole thing should work as long as @start_data and @end_date are set, but I'm stuck on how to finish this. I've been trying all sorts of things for the last hour and can't figure it out
Thanks in advance