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.