Multi-condition query without concatenating SQL strings during SQL server storage

Source: Internet
Author: User

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

Related Article

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.