[Reserved] program design process SQL statements effect of Where 1 = 1

In Asp.Net website or the website of the Java programming process, many times we can see the stitching written SQL statement can be seen when there is a front Where 1 = 1 this condition, in fact, Where 1 = 1 This is a identity, SQL statements, written in the form Where 1 = 1 can be better stitching query conditions.

Conclusion: Where a = 1 to identities splicing SQL statements 1 = 1 Where this statement segment mainly to better follow spliced ​​into complete SQL statement.

For example, the front page may be passed in two parameters and parameter values ​​Name Code, is the corresponding SQL query statement, but the two conditions can also be a full inquiry is empty, that does not pass the actual parameters, in the process, we often see the following wording.

SQL = String "the Where the Select * FROM TableA. 1. 1 =";
IF (string.IsNullOrWhiteSpace (the Name))
{
SQL = SQL string.Format + ( "the AND the Name = {0}", the Name);
}
IF (string.IsNullOrWhiteSpace (Code))
{
SQL = SQL string.Format + ( "the AND Code = {0}", Code);
}
after Where 1 = 1 using this identity, only determines whether the subsequent value of the property is empty, not empty directly into the spliced segment corresponding SQL statement. If you do not join Where 1 = 1 this condition, code readability becomes worse, several situations that may arise, the reader can think on their own under.

And the value of the Name Code (1) are empty, then the statement is not Sql Where the belt, is directly: Select * FRom TableA

(2) If the Name, Code there is a blank, empty when the other is not, Sql And this statement is not with a keyword, Sql final statement either as Select * FRom TableA Where Name = @ Name either as Select * FRom TableA Where Code = @ Code;

(3) If the Name, Code are not empty when the statement would contain AND keyword, but there will be no pre-Name AND keyword condition. Under imagine if you have 10 query, is not even judged that the query attribute is the first query field SQL statement. This judgment more trouble.

Of course, if no such an approach Where 1 = 1, there are kinds of methods can be somewhat easy to read, is defined separately for splicing fields sqlFilter query criteria, the final judgment sqlFilter is empty, if not empty, is taken after a few off the top of the sqlFilter AND character string to get the final query, the query stitching Sql in.

Note: The text reproduced from technology bloggers personal site IT technology small fun house , the original link program design process, the role of the SQL statement Where 1 = 1 _IT technology small fun house .

Guess you like

Origin blog.csdn.net/weixin_39650424/article/details/93380694