为什么有人会在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

其他回答

我发现这个模式在我测试或重复检查数据库上的东西时很有用,所以我可以很快地注释其他条件:

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

变成:

CREATE VIEW vTest AS
SELECT FROM Table WHERE 1=1 
--AND Table.Field=Value
--AND Table.IsValid=true

使“where 1=1”成为所有查询的标准,还可以通过将其替换为where 1= 0来简单地验证sql,当您有批量命令/文件时非常方便。

这也使得查找任何查询的from/join部分的结尾变得非常容易。甚至带有子查询的查询,如果缩进得当。

如果条件列表在编译时不知道,而是在运行时构建,则不必担心是否有一个或多个条件。你可以像这样生成它们:

and <condition>

然后把它们连在一起。1=1在开头,首字母和有关联。

我从来没见过这个用于任何注射保护,就像你说的,它似乎没有多大帮助。我曾看到它被用作一种实现方便。SQL查询引擎最终会忽略1=1,因此它不会对性能产生影响。

这里有一个密切相关的例子:使用SQL MERGE语句来更新目标表,使用源表中的所有值,其中没有可以连接的公共属性。

MERGE INTO Circles
   USING 
      (
        SELECT pi
         FROM Constants
      ) AS SourceTable
   ON 1 = 1
WHEN MATCHED THEN 
  UPDATE
     SET circumference = 2 * SourceTable.pi * radius;

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.