我正在C#中建立一些SQL查询。根据某些作为变量存储在代码中的条件,它会有所不同。
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”关键字。
有更好的解决方案吗?
Select 42
我们收到数十万条查询。(有趣的是试图寻找源头)
If I didn't use it, I would have to remember and check every time if "where" keyword was already added or not to the query
-这就是为什么要使用1 = 1
。无论如何,数据库引擎都会对其进行优化,因此尽管看起来很丑陋,但这是解决问题的最简单方法。
42 = 42
;-)