將WHERE 1 = 1
添加到基本查詢,然後將AND
添加到每個選定的條件。
肯定使用SqlParameter
將值傳遞給sql查詢。
public class Condition
{
public Func<bool> IsSelected { get; set; }
public string Text { get; set; }
public SqlParameter Value { get; set; }
}
var conditions = new[]
{
new Condition
{
IsSelected =() => checkBoxDate.Checked,
Text = "CreateDate >= @CreatedDate",
Value = new SqlParameter("@CreatedDate", new DateTime(2017, 8, 1))
},
new Condition
{
IsSelected =() => checkBoxUser.Checked,
Text = "User = @User",
Value = new SqlParameter("@User", "John")
},
new Condition
{
IsSelected =() => checkBoxNumber.Checked,
Text = "Number = @Number",
Value = new SqlParameter("@Number", 789)
},
new Condition
{
IsSelected =() => checkBoxId.Checked,
Text = "Id = @Id",
Value = new SqlParameter("@Id", 12)
}
}
var selectedConditions = conditions.Where(condition => condition.IsSelected()).ToList();
var baseQuery = "SELECT Id, Number, User, CreatedDate FROM MyTable WHERE 1 = 1";
var parameters = selectedConditions.Select(condition => condition.Value);
var commandText =
selectedConditions.Aggregate(new StringBuilder(),
(text, condition) =>
{
text.Append(" AND ");
text.Append(condition.Text);
return text;
},
(text) =>
{
text.Insert(0, baseQuery);
return text.ToString();
});
using (var connnection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.AddRange(parameters);
connection.Open();
// execute command
}
由於@jmoreno建議您不要將WHERE 1 = 1
添加到查詢中。然後SQL建設將看起來像下面的代碼 - 選擇你認爲更適合你的需求的方法。
var baseQuery = "SELECT Id, Number, User, CreatedDate FROM MyTable";
var selectedText = selectedConditions.Select(condition => condition.Text);
var commandText =
selectedConditions.Any()
? $"{baseQuery} WHERE {string.Join(" AND ", selectedText)}"
: baseQuery;
有什麼這麼棘手的呢? SELECT * From Table_Name WHERE Column1 ='「&variable&」'AND ......我假設你知道你的用戶會輸入多少個變量。如果不是僅僅使用一堆If ElseIF語句來構建它。 –
取決於用戶選擇的內容,除了很多其他之外還有其他內容嗎? – Dino
不是,您必須檢查每個條件,看看是否需要添加到查詢中。 –