如何构建Dynamic @Para语句?

时间:2017-03-16 09:28:54

标签: c# sql parameters

如何使用两个不同的参数构造动态select语句。 我的代码没有参数工作正常,但如果我想在参数中转换它。

如果我使用@VehiNo@CustName转换代码。 请检查代码中的注释。

using (SqlConnection conn = new SqlConnection(dbConn))
{
    if (txtSearchVehicleNo.MaskCompleted)
    {
        sqlString = "Select * From Master Where VehiNo = '" + txtSearchVehicleNo.Text + "'";  // here i convert with @VehiNo
    }
    else if (!string.IsNullOrWhiteSpace(txtSearchMemberName.Text))
    {
        sqlString = "Select * From Master Where CustName = '" + txtSearchMemberName.Text + "'"; // here i convert with @CustName
    }

    using (SqlCommand cmd = new SqlCommand(sqlString, conn))
    {
        cmd.CommandType = CommandType.Text;
        // How to use following 2 in condition
        //cmd.Parameters.AddWithValue("@VehiNo", txtSearchVehicleNo.Text);
        //cmd.Parameters.AddWithValue("@CustName", txtSearchMemberName.Text);
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        dtMember.Load(reader);
    }
}

1 个答案:

答案 0 :(得分:0)

这个怎么样:

using (SqlConnection conn = new SqlConnection(dbConn))
{

    using (SqlCommand cmd = new SqlCommand())
    {
        string sqlString = string.Empty;
        if (txtSearchVehicleNo.MaskCompleted)
        {
            sqlString = "Select * From Master Where VehiNo = @VehiNo;";
            cmd.Parameters.AddWithValue("@VehiNo", txtSearchVehicleNo.Text);
        }
        else if (!string.IsNullOrWhiteSpace(txtSearchMemberName.Text))
        {
            sqlString = "Select * From Master Where CustName = @CustName;";
            cmd.Parameters.AddWithValue("@CustName", txtSearchMemberName.Text);
        }

        cmd.Connection = conn;
        cmd.CommandText = sqlString;

        cmd.CommandType = CommandType.Text;
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        dtMember.Load(reader);
    }
}