I am using a table visualization in Grafana and I want to filter the content of the table with a variable called "PC", of type query, showing a list of PC names.
The SQL sentence that I am using is the following:
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
DECLARE @PC AS NVARCHAR(255) = $PC;
DECLARE @pcFilter AS NVARCHAR(255) = '%' + @PC + '%'
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(PC)
FROM DATOS_GENERALES DG INNER JOIN OPERACION_MANUAL OM ON DG.RefId = OM.RefId
WHERE TimeStamp_UTC IS NOT NULL AND PC LIKE @pcFilter
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT Fecha, ' + @cols + ' FROM
(SELECT PC, CONVERT(NVARCHAR(8), TimeStamp_UTC, 112) AS Fecha,
(TiempoTest + 2 * Tiempo)/3600 AS TiempoTotal
FROM DATOS_GENERALES DG INNER JOIN OPERACION_MANUAL OM ON DG.RefId = OM.RefId
WHERE TimeStamp_UTC IS NOT NULL AND PC LIKE @pcFilter) AS A
PIVOT
(
SUM(TiempoTotal) FOR PC IN (' + @cols + ')
) AS P
ORDER BY Fecha DESC'
/* Original execution
EXECUTE(@query);
*/
-- Currently using execution
EXECUTE sp_executesql @query, N'@pcFilter nvarchar(255)', @pcFilter = @pcFilter
The variable pcFilter
is declared in order to take the value of the Grafana's dashboard variable PC
and then added to the WHERE
conditions.
Without declaring the variable and including the WHERE
condition the table is correctly shown, but with the code from above I get this error:
db query error: mssql: Must declare the scalar variable "@pcFilter".
Am I declaring in a wrong way this variable? If so, how should I do it?