c# adding a variable in a SQL dynamic pivot string

北城余情 提交于 2019-12-25 02:08:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!