Note that there are some explanatory texts on larger screens.

plurals
  1. POSql Server Query Date Issue
    primarykey
    data
    text
    <p>This executes correctly: (It is weird that I needed to use '' by the date for it to actually execute)</p> <pre><code>DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname) FROM [85137_PHY_Long_PG] c FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') set @query = 'SELECT statdate, ' + @cols + ' from ( select statdate, statcolumnname, statcolumnvalue from [85137_PHY_Long_PG] ) x pivot ( min(statcolumnvalue) for statcolumnname in (' + @cols + ') ) p WHERE statdate BETWEEN ''2012-04-01 12:15:00'' AND ''2012-04-01 12:45:00'' ORDER BY statdate' execute(@query) </code></pre> <p>Now I want to replace the dates with variables:</p> <pre><code>DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @from AS NVARCHAR(MAX), @to AS NVARCHAR(MAX); set @from = '2012-04-01 12:15:00' set @to = '2012-04-01 12:45:00' select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname) FROM [85137_PHY_Long_PG] c FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') set @query = 'SELECT statdate, ' + @cols + ' from ( select statdate, statcolumnname, statcolumnvalue from [85137_PHY_Long_PG] ) x pivot ( min(statcolumnvalue) for statcolumnname in (' + @cols + ') ) p WHERE statdate BETWEEN ''+@from+'' AND ''+@to+'' ORDER BY statdate' execute(@query) </code></pre> <p>I get the following error:<strong>Conversion failed when converting character string to smalldatetime data type</strong></p> <p>Changing the where statement to the following:</p> <pre><code>WHERE statdate BETWEEN ''+convert(smalldatetime,@from)+'' AND ''+convert(smalldatetime,@to)+'' ORDER BY statdate' </code></pre> <p>Still gives me the same error, just can't seem to replace the dates as variables</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload