我正在构建一些 SQL在 C# 中查询。它会根据在代码中存储为变量的某些条件而有所不同。
string Query="SELECT * FROM Table1 WHERE 1=1 ";
if (condition1)
Query += "AND Col1=0 ";
if (condition2)
Query += "AND Col2=1 ";
if (condition3)
Query += "AND Col3=2 ";
它有效,但测试 1=1 似乎并不优雅。如果我不使用它,我将不得不记住并每次检查是否已将“where”关键字添加到查询中。
有更好的解决方案吗?
最佳答案
将条件保存在列表中:
List<string> conditions = new List<string>();
if (condition1) conditions.Add("Col1=0");
//...
if (conditions.Any())
Query += " WHERE " + string.Join(" AND ", conditions.ToArray());
关于c# - 有没有比在开头使用 1=1 更好的动态构建 SQL WHERE 子句的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17321281/