Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>'' is not weird; it is a notation that enables apostrophes inside varchars. </p> <p>When concatenating make sure that you are not trying to concatenate anything other than (n)varchars and (n)chars because Sql Server will attempt to convert them to other datatypes; in your case, in smalldatetime. You might avoid this trouble by explicitly converting your parameter dates to nvarchars before/during concatenation, but better solution is to use <a href="http://msdn.microsoft.com/en-us/library/ms188001.aspx" rel="nofollow">sp_executesql</a> and parameters.</p> <p>If you leave parameters inside query:</p> <pre><code>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' </code></pre> <p>You can execute it with parameters:</p> <pre><code>exec sp_executesql @query, N'@from datetime, @to datetime', @from=@from_variable, @to=@to_variable </code></pre> <p>Where @from_variable and @to_variable are datetime variables defined earlier in batch.</p> <p><strong>UPDATE:</strong></p> <p>If your ultimate goal is to wrap this code in stored procedure, here is a template:</p> <pre><code>create proc MyProc (@dateFrom smalldatetime, @dateTo smalldatetime) as 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 @from AND @to ORDER BY statdate' exec sp_executesql @query, N'@from smalldatetime, @to smalldatetime', @from=@dateFrom, @to=@dateTo </code></pre>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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