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

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

    Here's a closely related example: using a SQL MERGE statement to update the target tabled using all values from the source table where there is no common attribute on which to join on e.g.

    MERGE INTO Circles
       USING 
          (
            SELECT pi
             FROM Constants
          ) AS SourceTable
       ON 1 = 1
    WHEN MATCHED THEN 
      UPDATE
         SET circumference = 2 * SourceTable.pi * radius;
    
    0 讨论(0)
  • 2020-11-22 07:47

    Having review all the answers i decided to perform some experiment like

    SELECT
    *
    FROM MyTable
    
    WHERE 1=1
    

    Then i checked with other numbers

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

    ect Having done all the checks, the query run town is the same. even without the where clause. I am not a fan of the syntax

    0 讨论(0)
  • 2020-11-22 07:48

    I've seen it used when the number of conditions can be variable.

    You can concatenate conditions using an " AND " string. Then, instead of counting the number of conditions you're passing in, you place a "WHERE 1=1" at the end of your stock SQL statement and throw on the concatenated conditions.

    Basically, it saves you having to do a test for conditions and then add a "WHERE" string before them.

    0 讨论(0)
  • 2020-11-22 07:48

    I do this usually when I am building dynamic SQL for a report which has many dropdown values a user can select. Since the user may or may not select the values from each dropdown, we end up getting a hard time figuring out which condition was the first where clause. So we pad up the query with a where 1=1 in the end and add all where clauses after that.

    Something like

    select column1, column2 from my table where 1=1 {name} {age};
    

    Then we would build the where clause like this and pass it as a parameter value

    string name_whereClause= ddlName.SelectedIndex > 0 ? "AND name ='"+ ddlName.SelectedValue+ "'" : "";
    

    As the where clause selection are unknown to us at runtime, so this helps us a great deal in finding whether to include an 'AND' or 'WHERE'.

    0 讨论(0)
  • 2020-11-22 07:49

    1 = 1 expression is commonly used in generated sql code. This expression can simplify sql generating code reducing number of conditional statements.

    0 讨论(0)
  • 2020-11-22 07:49

    If you came here searching for WHERE 1, note that WHERE 1 and WHERE 1=1 are identical. WHERE 1 is used rarely because some database systems reject it considering WHERE 1 not really being boolean.

    0 讨论(0)
提交回复
热议问题