Where 1 = 1? In SQL, writing such a sentence is the same as not writing it.
Select * from table1 where 1 = 1 is no different from select * from table1, and there are even many other statements, 1 <> 2, 'A' = 'A ', 'A' <> 'B' has only one purpose. The where condition is permanent, and the result is that no constraint is added.
This is used in SQL injection, for example, select * from table1 where name = 'lala 'forcibly adds select * from table1 where name = 'lala' or 1 = 1, which becomes a unrestricted query.
The most amazing use recently found is that 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.
Copy codeThe Code is as follows:
If (! Name. equals ("")){
SQL = SQL + "name = '" + name + "'";
}
If (! Age. equals ("")){
SQL = SQL + "age" + age + "'";
}
If (! Height. equals ("")){
SQL = SQL + "height = '" + height + "'";
}
If (! Weight. equals ("")){
SQL = SQL + "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 to check the conditions in the program
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.
Copy table
Create table_name as select * from Source_table where 1 = 1;
Copy table structure
Create table_name as select * from Source_table where 1 <> 1;