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

当前回答

这在必须使用动态查询in which in where的情况下很有用 子句,则必须附加一些筛选选项。比如,如果你包含选项0表示状态为非活动,1表示活动。根据选项,只有两个可用选项(0和1),但如果您想显示所有记录,可以方便地在close 1=1的位置包含。 见以下样本:

Declare @SearchValue    varchar(8) 
Declare @SQLQuery varchar(max) = '
Select [FirstName]
    ,[LastName]
    ,[MiddleName]
    ,[BirthDate]
,Case
    when [Status] = 0 then ''Inactive''
    when [Status] = 1 then ''Active''
end as [Status]'

Declare @SearchOption nvarchar(100)
If (@SearchValue = 'Active')
Begin
    Set @SearchOption = ' Where a.[Status] = 1'
End

If (@SearchValue = 'Inactive')
Begin
    Set @SearchOption = ' Where a.[Status] = 0'
End

If (@SearchValue = 'All')
Begin
    Set @SearchOption = ' Where 1=1'
End

Set @SQLQuery = @SQLQuery + @SearchOption

Exec(@SQLQuery);

其他回答

只是在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

在生产代码中看到了这一点,并向前辈寻求帮助。

他们的回答:

-我们使用1=1,所以当我们必须添加一个新的条件时,我们只需输入

and <condition>

然后继续做下去。

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.

间接相关:当使用1=2时:

CREATE TABLE New_table_name 
as 
select * 
FROM Old_table_name 
WHERE 1 = 2;

这将创建一个与旧表具有相同模式的新表。(非常方便,如果你想加载一些数据进行比较)

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

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