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
If only a single app is using the function, in this particular way as you mentioned ( so not joined/applied to another object) this should have been a sproc ! Add an oder by clause to the data returning query to receive the result set in a particular order.
There is always a risk your fn will be used by another dev, but not in the way you intended it to be used, causing issues of all kind. Performance being the one I would be worried about.
Is it just that you don't like the answer you are hearing? Truth is, order is only guaranteed with an order by clause. It's not an opinion, it is fact. There is no alternative if it is a guarantee you are looking for.
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;
For an inline TVF nothing will really work. Not only that, the inline TVF may even return more rows than you believe it should, and the rows will be trimmed after the TVF executed (basically a predicate in the TVF definition can be pulled out of the TVF and moved somewhere else in the query tree). See T-SQL functions do no imply a certain order of execution for an example of this happening.
Converting the inline TVF to a multi statement one will introduce some procedural order, since the statements cannot be executed out of order, but the TVF result may be re-ordered, sorted, split, spooled, basically mangled by the optimizer generated plan and in the end break your assumption about output order. I'm afraid if you must have a certain order of execution, cursors are your best friend.