Dynamic sorting of database query results _ MySQL-mysql tutorial

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... for most people, the first thing that comes to mind when ELSE executes pre-compiled queries may be through IF... A common problem with ELSE statements in public newsgroups is: "How can I return a sort 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.