Roles of where 1 = 1 in SQL

Source: Internet
Author: User

I personally think this articleArticleI wrote very well and used examples to explain the truth very clearly. I hope it will be helpful to you.

 

1 = 1 or 'A' = 'A', etc. The constant equation is the method to express true in the T-SQL. Because there is no such keyword or value as true in the T-SQL, the concept of true needs to be expressed with these constants.
You can also use 1 <> 1 or 1 = 2 to express false.

In terms of application security, using these formulas is the basic principle of SQL injection. Therefore, you must filter various sensitive characters when splicing SQL statements.

Of course, these formulas are useful. Today I saw a useful tip:

Query records from a table. These records are filtered by name, age, height, and weight. However, the number of specific filtering conditions is uncertain. For example, sometimes it is a combination of name and age, sometimes it is a combination of name, height and weight, and sometimes there is no condition.
What should I do?
The general method of concatenating SQL statements requires a judgment: add the where keyword before the first condition. However, to do so, you need to add a set of judgment logic to check whether the current condition is the first condition.

Here, we can omit the above judgment logic by introducing where 1 = 1.
How can this problem be solved?CodeAs follows:
String query = "select * From userinfo where 1 = 1"

If (_ name! = String. Empty)
{

Query + = "and name = '" + _ name + "'";
}
If (_ age! = String. Empty)
{

Query + = "and age = '" + _ age + "'";
}

If (_ height! = String. Empty)
{

Query + = "and Height = '" + _ height + "'";
}
If (_ weight! = String. Empty)
{

Query + = "and Weight = '" + _ weight + "'";
}

Of course, it is better not to splice SQL statements. Using ADO objects directly is the most convenient method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.