如何使用两个不同的参数构造动态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);
}
}
答案 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);
}
}