I have a view with a pivot function in it:
SELECT TOP (10000) PivotTable.BEZEICHNUNG, PivotTable.[29.01.2013] AS ...
FROM (SELECT l.LONGNAME AS BEZEICHNUNG, m.WASSPNN AS STAND, m.SMPDATE AS DATUM
FROM ...
WHERE l.PRJ_ID = '86WAA5') AS SourceTable PIVOT (AVG(STAND) FOR DATUM IN ([29.01.2013], [27.02.2013], [27.03.2013], [24.04.2013], ...)) AS PivotTable
WHERE ...
ORDER BY BEZEICHNUNG
This works just fine and displays all the hardcoded columns. Now I need to refactor this, so it takes dynamic column values depending on a Start and End date. I used this SO answer as a guideline
Heres the code to the procedure in question:
BEGIN
DECLARE @PivotQuery NVARCHAR(MAX)
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @ProjectID AS NVARCHAR(15)
SET NOCOUNT ON
SET @ProjectID = '86WAA5'
SET @PivotQuery = 'SELECT TOP (10000) BEZEICHNUNG,'+@cols+'
FROM (SELECT l.LONGNAME AS BEZEICHNUNG, m.WASSPNN AS STAND, m.SMPDATE AS DATUM
FROM ...
WHERE l.PRJ_ID = ' + @ProjectID + ') AS SourceTable
PIVOT (AVG(STAND) FOR DATUM IN ('+ @cols + ')) AS PivotTable
ORDER BY BEZEICHNUNG
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(m.SMPDATE)
FROM ...
WHERE l.PRJ_ID = '86WAA5' AND
m.SMPDATE BETWEEN @StartDate AND @EndDate
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
EXECUTE(@PivotQuery)
END
GO
As you can see, the PivotQuery is a string variable, which I feed with the results from the @cols variable.
The field SMPDATE
is of type DateTime.
If I I select it plainly it does get returned formatted as: 2010-01-01 00:00:00.000
If I run the SELECT STUFF(...)
query on its own, the returned date variables are formatted as: [Jan 01, 2012 12:00AM],[Jan 19, 2012 12:00AM],[...
I have the suspicion that this format mismatch is causing the stored procedure to return no values. How should I build this procedure properly to avoid this problems?
EDIT: Bluefeet has solved the problem. If somebody stumbles above this and wants to reuse this piece of code: The @PivotQuery variable is a string. As such the quotationmarks need to be added and escaped before inserting @ProjectId into it. The snippet would then look like this:
WHERE l.PRJ_ID = ''' + @ProjectID + ''') AS SourceTable
Without this, the project Id would be treated as an integer value, which in most cases is fine. But if you deal with Id like mine here, you need to treat this as a string.