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

后端 未结 19 2016
甜味超标
甜味超标 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:31

    Why would someone use WHERE 1=1 AND

    I've seen homespun frameworks do stuff like this (blush), as this allows lazy parsing practices to be applied to both the WHERE and AND Sql keywords.

    For example (I'm using C# as an example here), consider the conditional parsing of the following predicates in a Sql query string builder:

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

    The "benefit" of WHERE 1 = 1 means that no special code is needed:

    • For AND - whether zero, one or both predicates (Bars and Baz's) should be applied, which would determine whether the first AND is required. Since we already have at least one predicate with the 1 = 1, it means AND is always OK.
    • For no predicates at all - In the case where there are ZERO predicates, then the WHERE must be dropped. But again, we can be lazy, because we are again guarantee of at least one predicate.

    This is obviously a bad idea and would recommend using an established data access framework or ORM for parsing optional and conditional predicates in this way.

提交回复
热议问题