【发布时间】:2015-04-28 13:31:13
【问题描述】:
我正在尝试创建一个函数,该函数接受查询及其参数并返回 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();
当我运行应用程序时,我收到以下错误:
"必须声明变量@from"
但是,当我尝试声明它时(我已将声明作为注释),我收到以下消息:
变量名“@from”已经被声明。
变量名称在查询批处理或存储过程中必须是唯一的。
也许我在查询中做错了什么?
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+"
它工作正常,但我想避免可能的 Sql Injection,如果我声明它:
DECLARE @return_value int EXEC @return_value = [dbo].[ProcedureName] @from =@saledate
并将销售日期作为一个项目放在我的字典中我仍然有错误
必须声明变量@saledate
【问题讨论】:
-
您声明了“@saleDate”而不是“@from”(这是行 //“declare @saledate date ;” + )
-
@sabinbio 感谢您指出这一点。但是,即使我将其声明为“@from”,它仍然会给我带来同样的问题:(。我编辑了问题
-
@Ange1 - 这个问题与 dba.stackexchange.com 无关 - 它会自动移至 StackOverflow。
-
好的@MaxVernon 谢谢你指出这一点:)
-
如果从字符串中完全删除
declare @from date ;会发生什么?
标签: c#