Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order by a parameter

Hi i have a store procedure, where i do a select query. I want order this by an external parameter.

I post an minimal example:

CREATE PROCEDURE [dbo].[up_missioni_get_data]
@order VarChar(100)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT  * from missioni ORDER BY ...
END

What can i write in order by for do that?

thanks

like image 206
Luca Romagnoli Avatar asked Mar 04 '10 11:03

Luca Romagnoli


People also ask

What is ORDER BY and GROUP BY?

1. Group by statement is used to group the rows that have the same value. Whereas Order by statement sort the result-set either in ascending or in descending order. 2.

Can we use ORDER BY in function?

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

How do you use ORDER BY clause?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Is ORDER BY before or after GROUP BY?

Using Group By and Order By TogetherGROUP BY goes before the ORDER BY statement because the latter operates on the final result of the query.


1 Answers

You have 2 options, either use a CASE statement, or use dynamic sql

This would be an example of the CASE statement

DECLARE @Table TABLE(
        Col1 VARCHAR(10),
        Col2 VARCHAR(10)
)

DECLARE @OrderBy VARCHAR(100)

SET @OrderBy = 'Col1'

SELECT  *
FROM    @Table
ORDER BY 
        CASE
            WHEN @OrderBy = 'Col1' THEN Col1
            WHEN @OrderBy = 'Col2' THEN Col2
            ELSE Col1
        END

And this would be and example of dynamic sql

CREATE TABLE #Table (
        Col1 VARCHAR(10),
        Col2 VARCHAR(10)
)

DECLARE @OrderBy VARCHAR(100)

SET @OrderBy = 'Col1'

DECLARE @SqlString NVARCHAR(MAX)

SELECT @SqlString = 'SELECT * FROM #Table ORDER BY ' + @OrderBy

EXEC(@Sqlstring)

DROP TABLE #Table
like image 192
Adriaan Stander Avatar answered Nov 02 '22 03:11

Adriaan Stander