My ORDER BY clause works differently. If I am using a SELECT statement with ORDER BY everything is fine, all is sorted as i want.
But if I use TABLE-VALUED FUNCTION with the exact same SELECT statement inside that function it doesn't sort properly.
To clarify:
- That works 100% as it should.
DECLARE
@Number1_min as int = 1
@Number1_max as int = 100
@Number2_min as int = 1
@Number2_max as int = 100
SELECT ROW_NUMBER() over (order by Number1) LP,
Number1,
Number2
FROM TABLE1
WHERE
Number1>=@Number1_min and
Number1<=@Number1_max and
Number2>=@Number2_min and
Number2<=@Number2_max
ORDER BY LP
- That version doesn't sort properly. When I put that SELECT into a TABLE-VALUED FUNCTION it works only with a small number of result. If I recive not so many rows as a result, for example 30 rows, it works as it should and in a good order. The problem is when i recive something like 4000 rows of result it is not sorted properly.
CREATE FUNCTION [dbo].[Numbers]
(
@Number1_min int
@Number1_max int
@Number2_min int
@Number2_max int
)
RETURNS
@Table_Var TABLE
(
LP int,
Number1 int,
Number2 int
)
AS
BEGIN
Insert @Table_Var
(
LP,Number1,Number2
)
SELECT ROW_NUMBER() over (order by Number1) LP,
Number1,
Number2
FROM TABLE1
WHERE
Number1>=@Number1_min and
Number1<=@Number1_max and
Number2>=@Number2_min and
Number2<=@Number2_max
ORDER BY LP
RETURN
END
In both ways i recieve the same number of rows and the same data. The only difference is that when I am trying to use TABLE-VALUED FUNCTION it sorts parts of a result. For example that SELECT returns 5350 rows. Using a FUNTCTION I don't recive ORDERED BY from 1 to 5350, but something like 1-336 next 1365-1701, ... , 1026-1364, etc. The result is that i recieve all of those 5350 rows, but not ordered properly.
The key is that I would like to recieve good order just by calling this function, so I don't want any ordering of a function's result.
EDIT: I have found out, when WHERE clause is commented in TABLE_VALUED FUNCTION everything works fine. So the question is:
"Why does WHERE statement destroys an ORDER BY statement?"