我想創建一個函數,它接受一個查詢並且它的參數並返回一個SQLDataSource進一步綁定。必須聲明標量變量/變量已經聲明
功能是:
public static SqlDataSource getSqlSource(string sql, Dictionary<string, string> parameters)
{
SqlConnection con = new SqlConnection(ConnectionString);
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = sql;
foreach (KeyValuePair<string, string> item in parameters)
{
cmd.Parameters.Add(new SqlParameter(item.Key, item.Value));
}
SqlDataSource source = new SqlDataSource(ConnectionString, cmd.CommandText);
con.Close();
return source;
}
}
我試圖創建的查詢是:
string sql =
// "declare @from date ; " +
"with cte as " +
"(" +
"select username,count(username) as cc from SaleReport " +
"group by username " +
") " +
"select count(SaleReport.username) as numerKlientesh,distributorname from SaleReport " +
"inner join cte on SaleReport.username=cte.username " +
"where (SaleReport.saledate) <=CONVERT(date,@from) " +
"and (SaleReport.saledate)>=(dateadd(DAY,-10,CONVERT(date,@from))) " +
"and cc>1 and SaleReport.comboid not in (43,44,46,47) " +
"group by distributorname ";
Dictionary<String, String> Params = new Dictionary<String, String>();
Params.Add("@from", from);
SqlDataSource source = QueryManager.getSqlSource(sql, Params);
GridView1.DataSource = source;
GridView1.DataBind();
當我運行應用程序,我得到以下錯誤:
"Must declare the variable @from"
但是,當我嘗試聲明它時(我已將該聲明作爲註釋),我收到以下消息:
The variable name '@from' has already been declared.
Variable names must be unique within a query batch or stored procedure.
我在查詢中做錯了什麼?
EDIT1: 隨着SabinBio的建議,我已經輸出的查詢的結果如下:
declare @from date;
with cte as (
select username
,count(username) as cc
from SaleReport
group by username
)
select count(SaleReport.username) as numerKlientesh
,distributorname
from SaleReport
inner join cte on SaleReport.username=cte.username
where (SaleReport.saledate) <= CONVERT(date,@from)
and (SaleReport.saledate) >= (dateadd(DAY,-10,CONVERT(date,@from)))
and cc>1
and SaleReport.comboid not in (43,44,46,47)
group by distributorname
EDIT2
如果我把查詢在存儲過程中,我把它稱爲:
DECLARE @return_value int EXEC @return_value = [dbo].[ProcedureName] @from ="+from+"
它工作正常,bu T I想避免可能的SQL注入,如果我宣佈它想:
DECLARE @return_value int EXEC @return_value = [dbo].[ProcedureName] @from [email protected]
,並把saledate在我的字典中的項目還是有錯誤
Must declare the variable @saledate
您宣佈「@saleDate」不是「@from」(這是行//「declare @saledate date; 「+) –
@sabinbio謝謝你指出,但即使我聲明它是」@from「,它仍然帶給我同樣的問題:(。我編輯了問題 – Ange1
@ Ange1 - 這個問題是脫離主題爲dba.stackexchange.com - 它會自動移動到StackOverflow。 –