Why would someone use WHERE 1=1 AND in a SQL clause?

后端 未结 19 2002
甜味超标
甜味超标 2020-11-22 07:08

Why would someone use WHERE 1=1 AND in a SQL clause (Either SQL obtained through concatenated strings, either view definition)

I\'ve

19条回答
  •  礼貌的吻别
    2020-11-22 07:46

    Just adding a example code to Greg's answer:

    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
    

提交回复
热议问题