When #region a multi-conditional search, use the list collection to stitch the conditions (stitching SQL)
StringBuilder sql = new StringBuilder ("SELECT * from Phonenum");
list<string> wheres = new list<string> ();
if (Cbogroup.selectedindex! = 0)
{
Wheres. ADD ("ptypeid=" + cboGroup.Text.Split (' | ') [0]);
}
if (TxtSearchName.Text.Trim (). Length > 0)
{
Wheres. ADD ("PName like '%" + txtSearchName.Text.Trim () + "% '");
}
if (TxtSearchCellPhone.Text.Trim (). Length > 0)
{
Wheres. ADD ("Pcellphone like '%" + txtSearchCellPhone.Text.Trim () + "% '");
}
Determine if the user has selected a condition
if (wheres. Count > 0)
{
string wh = string. Join ("and", wheres. ToArray ());
Sql. Append ("where" + wh);
}
#endregion
#region Multi-conditional search using SQL statements with parameters
StringBuilder sql = new StringBuilder ("SELECT * from Phonenum");
list<string> wheres = new list<string> ();
list<sqlparameter> listparameter = new list<sqlparameter> ();
if (Cbogroup.selectedindex! = 0)
{
Wheres. ADD ("[email protected]");
Listparameter.add (New SqlParameter ("@typeid", CboGroup.Text.Split (' | ') [0]));
}
if (TxtSearchName.Text.Trim (). Length > 0)
{
Wheres. ADD ("PName like @pname");
PName like '% Joe '
PName liek '% ' [email protected]+ '% '
Listparameter.add (New SqlParameter ("@pname", "%" + txtSearchName.Text.Trim () + "%"));
}
if (TxtSearchCellPhone.Text.Trim (). Length > 0)
{
Wheres. ADD ("Pcellphone like @cellphone");
Listparameter.add (New SqlParameter ("@cellphone", "%" + txtSearchCellPhone.Text.Trim () + "%"));
}
Determine if the user has selected a condition
if (wheres. Count > 0)
{
string wh = string. Join ("and", wheres. ToArray ());
Sql. Append ("where" + wh);
}
Sqlhelper.executedatatable (SQL. ToString (), Listparameter.toarray ());
#endregion
Note: 1. If parameterized, the underlying uses dapper, then directly writes the parameter, then does not have the tube if, finally has all possible parameters to write the anonymous object, directly passes through, is possible. 2. If this is sqlparameters, refer to the 2nd example above
C # Multi-conditional splicing SQL