I am creating a tickets opened vs resolved per week gadget that reports back as far as the number of days that the user supplies.
My problem is that powergadgets (the gadget make I am using) throws an error when I try to run the below code:
The variable name ‘@NoOfDays’ has already been declared. Variable names must be unique within a query batch or stored procedure.
As you can see, I need to use this variable twice. If I add Declare @NoOfDays int at the beginning, powergadgets just crashes. I am pretty new to SQL, but in the past using a user-passed variable twice has never caused problems. What can I do to resolve the issue?
SELECT
a.resolved, b.opened,
a.weekClosed AS week,
a.yearClosed AS year,
CAST(a.yearClosed as varchar(5)) + ', ' + CAST(a.weekClosed as varchar(5)) AS period
FROM
(SELECT
TOP (100) PERCENT COUNT(DISTINCT TicketNbr) AS resolved,
{ fn WEEK(date_closed) } AS weekClosed,
{ fn YEAR(date_closed) } AS yearClosed
FROM v_rpt_Service
WHERE
(date_closed >= DateAdd(Day, DateDiff(Day, 0, GetDate()) - @NoOfDays, 0))
GROUP BY
{ fn WEEK(date_closed) }, { fn YEAR(date_closed) }
) AS a
LEFT OUTER JOIN
(SELECT TOP (100) PERCENT
COUNT(DISTINCT TicketNbr) AS opened,
{ fn WEEK(date_entered) } AS weekEntered,
{ fn YEAR(date_entered) } AS yearEntered
FROM
v_rpt_Service AS v_rpt_Service_1
WHERE
(date_entered > = DateAdd(Day, DateDiff(Day, 0, GetDate()) - @NoOfDays, 0))
GROUP BY
{ fn WEEK(date_entered) }, { fn YEAR(date_entered) }
) AS b ON a.weekClosed = b.weekEntered AND a.yearClosed = b.yearEntered
ORDER BY
year, week
This looks like a bug within Powergadgets, and the way it wraps queries. to me. It is examining the query, seeing two searches, each with a required variable, and then tries creating them as parameters. Hence you get the duplicate declaration error.
Suggestion – change the variable name in the second query, and then pass the value in twice (essentially creating two parameters). If it works, then we know that Powergadgets has a problem with variables being used twice in slightly different scope.