为什么有人会在SQL子句中使用WHERE 1=1 AND <条件>(通过连接字符串获得的SQL,或者视图定义)

我在某个地方看到过,这将用于防止SQL注入,但这看起来非常奇怪。

如果有一个注入WHERE 1=1和注入OR 1=1将有相同的结果注入OR 1=1。

稍后编辑:视图定义中的用法如何?


谢谢你的回答。

尽管如此, 我不明白为什么有人会使用这种结构来定义视图,或者在存储过程中使用它。

举个例子:

CREATE VIEW vTest AS
SELECT FROM Table WHERE 1=1 AND table.Field=Value

当前回答

只是在Greg的回答中添加了一个示例代码:

dim sqlstmt as new StringBuilder
sqlstmt.add("SELECT * FROM Products")
sqlstmt.add(" WHERE 1=1") 

''// From now on you don't have to worry if you must 
''// append AND or WHERE because you know the WHERE is there
If ProductCategoryID <> 0 then
  sqlstmt.AppendFormat(" AND ProductCategoryID = {0}", trim(ProductCategoryID))
end if
If MinimunPrice > 0 then
  sqlstmt.AppendFormat(" AND Price >= {0}", trim(MinimunPrice))
end if

其他回答

似乎是一种懒惰的方式,总是知道WHERE子句已经定义,并允许您继续添加条件,而不必检查它是否是第一个条件。

我曾见过在条件数量可变的情况下使用这种方法。

您可以使用“AND”字符串连接条件。然后,不计算传入的条件的数量,而是在stock SQL语句的末尾放置“WHERE 1=1”,并抛出连接的条件。

基本上,它使您不必对条件进行测试,然后在它们之前添加“WHERE”字符串。

回顾了所有的答案,我决定做一些实验

SELECT
*
FROM MyTable

WHERE 1=1

然后我用其他号码核对了一下

WHERE 2=2
WHERE 10=10
WHERE 99=99

等 在完成所有检查之后,查询run town是相同的。即使没有where从句。我不喜欢这种语法

Using a predicate like 1=1 is a normal hint sometimes used to force the access plan to use or not use an index scan. The reason why this is used is when you are using a multi-nested joined query with many predicates in the where clause where sometimes even using all of the indexes causes the access plan to read each table - a full table scan. This is just 1 of many hints used by DBAs to trick a dbms into using a more efficient path. Just don't throw one in; you need a dba to analyze the query since it doesn't always work.

为什么有人会使用WHERE 1=1 AND <适当条件>

我曾经见过简单的框架做这样的事情(脸红),因为这允许将惰性解析实践应用于WHERE和and Sql关键字。

例如(我在这里使用c#作为示例),考虑在Sql查询字符串构建器中对以下谓词的条件解析:

var sqlQuery = "SELECT * FROM FOOS WHERE 1 = 1"
if (shouldFilterForBars)
{
    sqlQuery = sqlQuery + " AND Bars > 3";
}
if (shouldFilterForBaz)
{
    sqlQuery = sqlQuery + " AND Baz < 12";
}

WHERE 1 = 1的“好处”意味着不需要特殊的代码:

对于AND——应该应用零、一个或两个谓词(Bars和Baz’s),这将决定是否需要第一个AND。因为我们已经有了至少一个1 = 1的谓词,它意味着AND总是OK的。 对于根本没有谓词的情况-在有0个谓词的情况下,则必须删除where。但同样,我们可以偷懒,因为我们再次保证至少有一个谓词。

这显然是一个坏主意,建议使用已建立的数据访问框架或ORM以这种方式解析可选和条件谓词。