简体   繁体   English

从表值 function 返回的订购结果

[英]Ordering results returned from table valued function

I have a user defined function that returns a table.我有一个用户定义的 function 返回一个表。 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.问题是这个表需要根据复杂的标准进行排序,因此它不应该由 function 调用者排序,而是需要在 function 本身中排序。

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?是否可以将订单移动到 function 并从 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. 您可以如下所示使用order by。 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 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.如果您准备接受唯一的排序结果,那么执行此操作的一种方法是将 PK 添加到返回表中。

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.注意:这个问题很旧,但还没有得到正确的回答,除了说除了添加一个排序列之外无法完成,这不是 OP 要求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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