我想为select语句编写参数化查询。但它给出了“必须声明变量'@'的例外情况。”如何声明这个变量。
我的代码如下:
SqlConnection con = null;
SqlCommand cmd = null;
try
{
//int @[MONTH_FOR], @[YEAR_FOR];
con = new SqlConnection("Data Source=192.168.10.3;Initial Catalog=GPSTrainees;user id=gp;password=gp");
con.Open();
string select = @"SELECT [COMPONENT_NAME] ,[COMPONENT_AMOUNT]
FROM [GoalPlanForTrainees].[gp].[TEAM_FUNDS_DETAILS]
WHERE [MONTH_FOR] = @[MONTH_FOR] AND [YEAR_FOR] = @[YEAR_FOR]";
cmd = new SqlCommand(select, con);
cmd.Parameters.Add(new SqlParameter("@[MONTH_FOR]", Convert.ToInt32( TextBox1.Text.Trim())));
cmd.Parameters.Add(new SqlParameter("@[YEAR_FOR]",Convert.ToInt32(TextBox2.Text.Trim())));
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(select, con);
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}`enter code here`
答案 0 :(得分:0)
将变量声明放在sql语句中。所以移动int @ [MONTH_FOR],@ [YEAR_FOR]; 至 @“int @ [MONTH_FOR],@ [YEAR_FOR]; SELECT [COMPONENT_NAME],[COMPONENT_AMOUNT] FROM [GoalPlanForTrainees]。[gp]。[TEAM_FUNDS_DETAILS] WHERE [MONTH_FOR] = @ [MONTH_FOR]和[YEAR_FOR] = @ [YEAR_FOR ]“;
Cheers Tigger
答案 1 :(得分:0)
创建参数时,请删除参数名称前面的“@”。像这样:
cmd.Parameters.Add(new SqlParameter("[MONTH_FOR]", Convert.ToInt32(TextBox1.Text.Trim())));
希望这应该有所帮助。
答案 2 :(得分:0)
试试这个
int MONTH_FOR=@monthFor
command.Parameters.Add(MONTH_FOR, SqlDbType.int).Value = value