繁体   English   中英

SQL 中带有条件“and”的嵌套 If 语句

[英]Nested If statement with Conditional “and” in SQL

我有这行代码

string sqlQuery = "SELECT studentid,StudentName,age,contact FROM tblStudent2 ";

if (txtStudentName.Text != "" && txtStudentId.Text != "" && txtAge.Text != "" && txtContact.Text != "")
{
    sqlQuery += " Where ";

    if (txtStudentName.Text != "")
    {
        sqlQuery += "studentId = '" + txtStudentName.Text + "'";
    }
    sqlQuery += " and ";

    if (txtStudentId.Text != "")
    {
        sqlQuery += "studentId = '" + txtStudentId.Text + "'";
    }
    sqlQuery += " and ";

    if (txtAge.Text != "")
    {
        sqlQuery += "age ='" + txtAge.Text + "'";
    }

    sqlQuery += " and ";

    if (txtContact.Text != "")
    {
        sqlQuery += " FROM tblStudent2 Where contact ='" + txtContact.Text + "'";
    }
}

我的问题目标是 select 从表( tblStudent2 )。 与此 SQL 声明

"SELECT studentid,StudentName,age,contact FROM tblStudent2" + "and (TableColumns) and (TableColumns)""

但是目标是在嵌套的 IF 参数之间添加“and”,如果我要将其添加到 if 语句中,如果我 append 是“and”,则生成的 sqlQuery 将导致“and”作为句子的最后一个单词“ 单词。

我建议在没有 boolean 的情况下编写此逻辑:

string sqlQuery = "SELECT studentid,StudentName,age,contact FROM tblStudent2";
string sqlWhere = ""
if (txtStudentName.Text != "")
    {
        sqlWhere += "StudentName = '" + txtStudentName.Text + "' and ";
    }
if (txtStudentId.Text != "")
    {
        sqlWhere += "studentId = '" + txtStudentId.Text + "' and ";
    }
if (txtAge.Text != "")
    {
        sqlWhere += "age ='" + txtAge.Text + "' and ";
    }
if (txtContact.Text != "")
    {
        sqlWhere += "contact ='" + txtContact.Text + "' and ";
    }
if (sqlWhere != "") {
    sqlQuery += " WHERE " + sqlWhere.Substring(0, myString.Length-5);
}

也就是说,您的代码有一个主要问题。 您正在使用用户输入值修改查询字符串——这既是由于 SQL 注入,也是由于意外(且难以调试)语法错误。 这是非常危险的。 您应该参数化查询,所以它看起来更像:

if (txtStudentName.Text != "")
    {
        sqlWhere += "StudentName = @StudentName and "
    }

(等等)。

然后在执行时将参数传递给查询。

最好将 append 'AND' 放在if条件中的每个语句的末尾,并删除最后一个,如下所示:

string sqlQuery = "SELECT studentid,StudentName,age,contact FROM tblStudent2";
bool flag = false;
if (txtStudentName.Text != "")
    {
        sqlQuery += "StudentName = '" + txtStudentName.Text + "' and ";
        flag = true;
    }
if (txtStudentId.Text != "")
    {
        sqlQuery += "studentId = '" + txtStudentId.Text + "' and ";
        flag = true;
    }
if (txtAge.Text != "")
    {
        sqlQuery += "age ='" + txtAge.Text + "' and ";
        flag  = true;
    }
if (txtContact.Text != "")
    {
        sqlQuery += "contact ='" + txtContact.Text + "' and ";
        flag = true;
    }
if (flag == true){
    sqlQuery += " WHERE " + sqlQuery.Substring(0, myString.Length-5);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM