Dynamic sorting of database query results (1)

Source: Internet
Author: User
Tags sql server query

In a public newsgroup, a common problem occurs: "How can we return a sorted output based on the parameters passed to the stored procedure ?". With the help of some high-level experts, I have developed several solutions to this problem.
1. Use IF... ELSE to execute the prepared Query
For most people, the first thought might be: execute one of several pre-written queries using the IF... ELSE statement. For example, if you want to obtain a Shipper sorting list from the Northwind database query, the called code is issued to specify a column as a stored procedure parameter, the stored procedure sorts the output results based on the column. Listing 1 shows a possible implementation of this stored procedure (GetSortedShippers stored procedure ).
[Listing 1: use IF... ELSE to execute one of multiple prepared Queries]
Create proc GetSortedShippers
@ OrdSeq AS int
AS
IF @ OrdSeq = 1
SELECT * FROM Shippers order by ShipperID
Else if @ OrdSeq = 2
SELECT * FROM Shippers order by CompanyName
Else if @ OrdSeq = 3
SELECT * FROM Shippers order by Phone

The advantage of this method is that the code is simple and easy to understand. The SQL Server query optimizer can create a query optimization plan for each SELECT query to ensure the optimal performance of the Code. The main drawback of this method is that if the query requirements change, you must modify multiple independent SELECT queries-here there are three.

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.