问题
I am trying to show the results of a dynamic pivot in a c# datagridview. So far I have got the following code but I am stumped as how to incorporate the @Date variable in the @query string. What am I missing here? The code works fine with hard coded dates and as it is returns Additional information: Incorrect syntax near '@Date'. Please help,
Thanks, A
da2.SelectCommand = new SqlCommand(@"DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(currency)
FROM Alpha.dbo.Beta
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT Customer, ' + @cols + ' FROM
(
SELECT
Customer, Amount, Currency
FROM Alpha.dbo.Beta
WHERE Date Between ''2010-01-01'' and '@Date' ----PROBLEM AREA----
) x
PIVOT
(
SUM(Amount)
for Currency in (' + @cols + ')
) AS pvt
ORDER BY Customer; '
execute(@query)", MyConnection);
da2.SelectCommand.Parameters.Add("Date", SqlDbType.DateTime).Value = dateTimePicker4.Text;
ds2.Clear();
da2.Fill(ds2);
回答1:
Correct your code as:
da2.SelectCommand.Parameters.Add("@Date", SqlDbType.DateTime);
da2.SelectCommand.Parameters["@Date"].Value = dateTimePicker4.Text;
Also, use stored procedure
instead the query.
来源:https://stackoverflow.com/questions/21315546/c-sharp-adding-a-variable-in-a-sql-dynamic-pivot-string