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
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;