簡體   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