In the process of paging data using temporary tables, it is found that the query statement conditions are passed through the stored procedure parameters. The parameter conditions cannot be directly used after the SQL where statements are added. There is only one solution to this problem, it is to concatenate SQL statements and conditions into an SQL string and then execute it. It is troublesome to concatenate SQL strings. If the SQL statement is simple, it is better to handle it, if hundreds of rows are stored, it will be very painful.
I found a better solution on the Internet. I suddenly found that "Multi-condition query is achieved without concatenating SQL strings in SQL Server Stored Procedures ".ArticleAfter a closer look, I really felt like a village. I would like to share this with you and make a record for myself.
The following is a solution to multi-condition query without concatenating SQL strings.
The first method is the feeling.CodeSome Redundancy
If (@ adddate is not null) and (@ name <> '')
Select * from table where adddate = @ adddate and name = @ name
Else if (@ adddate is not null) and (@ name = '')
Select * from table where adddate = @ adddate
Else if (@ adddate is null) and (@ name <> '')
Select * from table where and name = @ name
Else if (@ adddate is null) and (@ name = '')
Select * from table
The second method is
Select * from table where (adddate = @ adddate or @ adddate is null) and (name = @ name or @ name = '')
The third method is
Select * from table where
Adddate = case @ adddate is null then adddate else @ adddate end,
Name = case @ name when'' then name else @ name end