I am trying to create a function which takes a query and it's parameters and returns a SQLDataSource for further binding.
The function is:
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;
}
}
The query I am trying to create is:
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();
When I run the application, I get the following error:
"Must declare the variable @from"
But, when I try to declare it (I have put the declaration as a comment ) I get this message:
The variable name '@from' has already been declared.
Variable names must be unique within a query batch or stored procedure.
Am i doing something wrong in the query perhaps?
EDIT1: With the suggestion of SabinBio, I have outputted the result of the query as following:
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
If I put the query in a stored procedure, and I call it as :
DECLARE @return_value int EXEC @return_value = [dbo].[ProcedureName] @from ="+from+"
it works fine, but I want to avoid possible Sql Injection and if I declare it like:
DECLARE @return_value int EXEC @return_value = [dbo].[ProcedureName] @from =@saledate
and put the saledate as an item in my dictionary I still have the error
Must declare the variable @saledate