SQL where 1 = 1

Source: Internet
Author: User

When the number of query conditions is not fixed, 1 = 1 can easily regulate the statement. For example, a query may have name, age, height, and weight constraints, or none. What should I do?

String SQL = select * From Table1 where 1 = 1

Why do I need to write additional 1 = 1? Now you know.

If (! Name. Equals ("")){
SQL = SQL + "and name = '" + name + "'";
}
If (! Age. Equals ("")){
SQL = SQL + "and age'" + age + "'";
}
If (! Height. Equals ("")){
SQL = SQL + "and Height = '" + height + "'";
}
If (! Weight. Equals ("")){
SQL = SQL + "and Weight = '" + weight + "'";
}

If you do not enter 1 = 1, you must determine whether there is a where clause in front of every query condition that is not empty. Otherwise, you must add the WHERE clause in the first clause.

Where 1 = 1 is written for DetectionProgramCondition Detection
For example, there are three parameters A, B, and C.
@ SQL = select * From tb'
All three parameters can be empty.
In this case, if you want to construct statements, it will be troublesome to check and write statements one by one.
For example
If @ A is not null
@ SQL = @ SQL + "where a = '+ @
If @ B is not null
How do you write it here? Do you want to add where or directly use and ?, Check whether @ A is null.

After where 1 = 1 is used, there is no such problem. If and is used, and or is used, or is used directly.

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.