简体   繁体   中英

Ordering results returned from table valued function

I have a user defined function that returns a table. The problem is that this table needs to be sorted based on complex criteria and due to this it shouldn't be sorted by the function caller but needs to be sorted in the function itself.

Simplified example

select * 
from custom_function('param1', 'param2' ...) 
order by 
complex criteria 1,
complex criteria 2....

Is it possible to move order by into function and to get ordered results from select?

You can't sort the table directly, but you can add a column specifying the ordering. So, define the function as:

select . . .,
       row_number() over (order by <complex ordering criteria>) ord
. . .

Then you can call it as:

select f.*
from dbo.func(. . .) f
order by ord;

You can use order by as shown below. Let the Table-Valued Function be:

    CREATE FUNCTION ReturnTableTOrder()
    RETURNS @returnList TABLE (Col1 char(1), Col2 int)
    AS
    BEGIN   

         INSERT INTO @returnList
         SELECT 'A',5 Union All
         SELECT 'D',2 Union All
         SELECT 'B',4 Union All
         SELECT 'E',1 Union All
         SELECT 'C',3 

     RETURN

    END

You can order by Column Ordinal Position

    Select * from ReturnTableTOrder()
    Order by 1

o/p

Col1  Col2
 A     5
 B     4
 C     3
 D     2
 E     1

and for below query,

    Select * from ReturnTableTOrder()
    Order by 2

output is

Col1  Col2
 E     1
 D     2
 C     3
 B     4
 A     5

One way of doing this, if you are prepared to accept unique sorted results, is to add a PK to the return table.

CREATE OR ALTER FUNCTION MyFunc ()
    RETURNS @tblArray TABLE (Element VARCHAR(900) PRIMARY KEY WITH (IGNORE_DUP_KEY = ON))

AS BEGIN

    INSERT INTO @tblArray VALUES ('c'),('b'),('a')  
    RETURN

END

This returns a recordset containing

Element
a
b
c

Note: This question is old but it hasn't been answered properly yet, other than to say it can't be done except by adding a sort column, which isn't what the OP asked for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM