SQL语句错误关键字' WHERE'附近的语法错误

时间:2015-04-10 01:31:15

标签: sql asp.net

当我调用AND SQL语句时,我收到此错误:

  

关键字“WHERE”附近的语法不正确

我做错了什么?

public static dsCustomer RetrieveMultipleCustomers(int CustID = 0, string CustLast = null, string CustPhone = null, string CustEmail = null)
{
    dsCustomer DS;
    OleDbConnection connection = Connection();
    OleDbDataAdapter sqlDA;
    bool blnSubSelect = false;
    string strSubSelect = "Select * from Customer";
    if (CustID != 0)
    {
        strSubSelect = strSubSelect + " where CustID = " + CustID;
        blnSubSelect = true;
    }
    else
    {
        if (CustLast != null)
        {
            strSubSelect = strSubSelect + " where CustLast ='" + CustLast + "'";
            blnSubSelect = true;
        }
        if (CustPhone !=null && CustEmail==null && CustLast==null)
        {
            strSubSelect = strSubSelect + " where CustPhone ='" + CustPhone + "'";
        }

        if (CustEmail != null && CustPhone == null && CustLast ==null)
        {
            strSubSelect = strSubSelect + " where CustEmail = '" + CustEmail + "'";
        }

        if (CustLast != null && CustPhone != null && CustEmail ==null)
        {
            strSubSelect = strSubSelect + " WHERE CustLast ='"+CustLast+"' AND CustPhone ='"+CustPhone+"'";
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用“AND”以这种方式添加这些sql:

    public static dsCustomer RetrieveMultipleCustomers(int CustID = 0, string CustLast = null, string CustPhone = null, string CustEmail = null)
    {
        dsCustomer DS;
        OleDbConnection connection = Connection();
        OleDbDataAdapter sqlDA;
        bool blnSubSelect = false;
        string strSubSelect = "Select * from Customer where 1=1 ";
        if (CustID != 0)
        {
            strSubSelect = strSubSelect + " AND CustID = " + CustID;
            blnSubSelect = true;
        }
        else
        {
            if (CustLast != null)
            {
                strSubSelect = strSubSelect + " AND CustLast ='" + CustLast + "'";
                blnSubSelect = true;
            }
            if (CustPhone != null && CustEmail == null && CustLast == null)
            {
                strSubSelect = strSubSelect + " AND CustPhone ='" + CustPhone + "'";
            }

            if (CustEmail != null && CustPhone == null && CustLast == null)
            {
                strSubSelect = strSubSelect + " AND CustEmail = '" + CustEmail + "'";
            }

            if (CustLast != null && CustPhone != null && CustEmail == null)
            {
                strSubSelect = strSubSelect + " AND CustLast ='" + CustLast + "' AND CustPhone ='" + CustPhone + "'";
            }

        }
    }