SQL Server Order By In a SQL Table Valued Function

zlwx9yxi  于 2024-01-05  发布在  其他
关注(0)|答案(4)|浏览(90)

I've read about this problem on a few different sites, but I still don't understand the solution. From what I understand, SQL will optimize the query in the function and sometimes the Order By clause will be ignored. How can you sort results?

How can I sort results in a simple table valued function like this?

Create function [dbo].fTest

--Input Parameters
(@competitionID int)

--Returns a table
RETURNS @table TABLE (CompetitionID int )

as

BEGIN
    Insert Into @table (CompetitionID)
    select CompetitionID from Competition order by CompetitionID desc
    RETURN
END

UPDATE

I found inserting a primary key identity field seems to help (as mentioned in the answer posted Martin Smith). Is this a good solution?

--Returns a table
RETURNS @table TABLE
(
    SortID int IDENTITY(1,1) PRIMARY KEY,
    CompetitionID int 
)

In reference to Martin's answer below, sorting outside of the select statement isn't that easy in my situation. My posted example is a stripped down version, but my real-life issue involves a more complicated order by case clause for custom sorting. In addition to that, I'm calling this function in an MVC controller with a LINQ query, which means that custom sorting would have to be added to the LINQ query. That's beyond my ability at this point.

If adding the identity field is a safe solution, I'm happy to go with that. It's simple and easy.

nsc4cvqm

nsc4cvqm1#

The order by needs to be in the statement that selects from the function.

SELECT CompetitionId
FROM [dbo].fTest()
ORDER BY CompetitionId

This is the only way to get reliable results that are assured to not suddenly break in the future .

sgtfey8w

sgtfey8w2#

This is just a bit of an ingenious workaround and only useful in some scenarios but it worked beautiful for what I needed: you can create a stored procedure that does a select * from the function with the desired order by clause and use that instead...

e0uiprwp

e0uiprwp3#

You can duplicate your result table (declare a table var @X and @ret_X ).

Then perform your actions on the @X table and make the following statement as last statement in your function.

insert into @ret_X 
 select top 10000 * from @X
 order by (column_of_choise) desc

This gives me the sorting I want.

34gzjxbg

34gzjxbg4#

Best way is to return your data from the back end and do the sorting Using a linq query in you c sharp code

相关问题