guarantee order of table valued function results

前端 未结 4 1804
予麋鹿
予麋鹿 2021-01-28 11:04

PREMISE: The application code cannot be changed. The conditions are very specific. I am looking for something off the books, a last resort workaround if you

4条回答
  •  抹茶落季
    2021-01-28 11:54

    You'll have a better shot at a predictable query plan if you use a single-statement TVF instead of a multistatement TVF. ROW_NUMBER OVER should enfore the ordering you want in your RES2 query, and if it doesn't, just put it inside a CTE and order by your row number column. See below.

    CREATE FUNCTION [dbo].[MyFunction]
    (
    /*
    Parameters
    */
    )
    RETURNS TABLE
    RETURN
    WITH res2
    (
        rn,
        Varchar3Col,
        DateTimeCol,
        Varchar50Col
    )
    AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY action_time) AS rn,
            Varchar3Col,
            action_time AS DateTimeCol,
            Varchar50Col
        FROM
    /*
            [...from statement...]
    */      
    )
    SELECT
        rn,
        Varchar3Col,
        DateTimeCol,
        Varchar50Col
    FROM
        res2
    ORDER BY
        rn;
    

提交回复
热议问题