我正在创建一个asp web表单页面,此部分正在构建查询,并且在添加boatYear
部件时引发异常。在数据库中它是一个smallint
。SQL异常关键字'And'附近的语法错误
类型“System.Data.SqlClient.SqlException”的异常出现在System.Data.dll中,但在用户代码中没有处理
附加信息:关键字“与”附近有语法错误。
查询:
string qs = Request.QueryString["dir"].ToString();
string sql = "Select * From Boats ";
string boatClass = "";
string boatYear = "";
string boatMake = "";
string boatUsedNew = "";
if (qs.Equals("f"))
{
boatClass = (string)Session["class"];
boatYear = (string)Session["year"];
boatMake = (string)Session["make"]; ;
boatUsedNew = (string)Session["usednew"];
}
string where = "";
if (qs != "b")
{
if (boatClass != "all" && boatClass != "")
{
where = "Where Class = '" + boatClass + "'";
}
if (boatYear != "all" && boatYear != "")
{
if (where == "")
{
where += "Where ";
}
else
{
where += " AND ";
}
where += "Year = " + boatYear;
}
if (boatMake != "all" && boatMake != "")
{
if (where == "")
{
where += "Where ";
}
else
{
where += " AND ";
}
where += "Make = '" + boatMake + "'";
}
if (boatUsedNew != "all" && boatUsedNew != "")
{
if (where == "")
{
where += "Where ";
}
else
{
where += " AND ";
}
where += "UsedOrNew = '" + boatUsedNew + "'";
}
sql += where;
Session["sql"] = sql;
}
else
{
sql = (string)Session["sql"];
}
您是否尝试打印出您的SQL? –
这是非常糟糕的做法,它容易出现很多错误。它很难阅读......你应该简单地调试生成的sql。你的条件很奇怪。你知道你可以使用string.IsNullOrEmpty()正确吗? – JonH
呃。为什么不'WHERE 1 = 1',那么你可以简单地使用'AND'来添加新的子句。这会大大地降低你的代码... –