如果Else使用参数查询

时间:2017-07-16 16:43:59

标签: c# sql asp.net asp.net-mvc

我收到错误2x:

  

名为' q'的本地或参数不能在此范围内声明,因为该名称在封闭的本地范围内用于定义本地或参数

我在这里做错了什么?我在视图中有一个下拉列表,然后将值传递给@dropdowncategory参数

这是我的代码:

cmd.Connection = con;
string dropdownsearch = "@dropdowncategory";
string q;
if (dropdownsearch == "ID")
{
    string q = "SELECT * FROM accounts WHERE id = @id";
}
else
{
    string q = "SELECT * FROM accounts WHERE name = @name";
}

cmd.Parameters.AddRange(queryParams.ToArray());
cmd.CommandText = q;
con.Open();

2 个答案:

答案 0 :(得分:3)

您所做错的是,您只在qif分支的scope(*)中定义else。这意味着它不存在于它之外。

这应该有效:

string q;
if (dropdownsearch == "ID")
{
    q = "SELECT * FROM accounts WHERE id = @id";
}
else
{
    q = "SELECT * FROM accounts WHERE name = @name";
}

cmd.Parameters.AddRange(queryParams.ToArray());
cmd.CommandText = q;
con.Open();

或者,您可以执行以下操作:

string q = dropdownsearch == "ID"
    ? "SELECT * FROM accounts WHERE id = @id"
    : "SELECT * FROM accounts WHERE name = @name";
cmd.CommandText = q;

或者一路走向简洁,完全摆脱q

cmd.CommandText = dropdownsearch == "ID"
    ? "SELECT * FROM accounts WHERE id = @id"
    : "SELECT * FROM accounts WHERE name = @name";

(*)感谢@Uwe Keim建议链接!

答案 1 :(得分:1)

q的范围在括号内(if / else)。在外面声明它,你的代码将编译。

cmd.Connection = con;
string dropdownsearch = "@dropdowncategory";
string q;
if (dropdownsearch == "ID")
{
    q = "SELECT * FROM accounts WHERE id = @id";
}
else
{
    q = "SELECT * FROM accounts WHERE name = @name";
}

cmd.Parameters.AddRange(queryParams.ToArray());
cmd.CommandText = q;
con.Open();