paparazzo
paparazzo

Reputation: 45096

TSQL Sort Order Based On Order In The In Clasuse

The scenario is first run an expensive sorted query and save the first 100,000 Primary Key (Int32) in a .NET List. Then retrieve detail 100 rows at a time from about a dozen tables. The format of of the detail query is:

    select ... from DetailA where PK in (sorted list of 100 PK).  

The problem is the return is not sorted by the order in the in clause. Need the detail to be sorted. Don't want apply the sort that was used to create 100,000 master list as that is an expensive and messy sort.

My thought is to load the 100 PK into #tempSort table and use that for the sort. Is there a better approach?

Currently getting the detail one row at a time using SQLDataReader and that takes about 2 seconds. Tested getting all at once using a DataSet with multiple DataTables and that was slower than one row at a time using a SQLDataReader by a factor of 3. This data is being loaded into objects so need for advanced features of a DataSet.

I do not want to save the 100,000 master results in a #temp as this is a big active database and need to move load to the client.

Trying the Table-Value Parameters as suggested.
Is this the proper syntax?

    CREATE TYPE sID100 AS TABLE 
    ( sID INT, sortOrder INT );
    GO

    /* Declare a variable that references the type. */
    DECLARE @sID100 AS sID100;

    /* Add data to the table variable. */
    INSERT INTO @sID100  (sID, sortOrder) 
    values (100, 1), (200,2), (50,3);

    Select * from @sID100;
    select docSVsys.sID, docSVsys.addDate 
    from docSVsys 
    join @sID100 as [sID100] 
    on [sID100].sID = docSVsys.sID 
    order by [sID100].sortOrder
    GO

    Drop TYPE sID100 

Above is not optimal. I am learning but in C# can create a DataTable and pass it to a stored procedure using Tabel-Value Parameters. Exactly what Martin said in the comment but it took some research before I understood his words.

Upvotes: 1

Views: 203

Answers (1)

gbn
gbn

Reputation: 432230

The order of the PKs in the IN clause is irrelevant.
Only the outermost ORDER BY matters: any order is arbitrary if not specified

select ...
from DetailA
where PK in (sorted list of 100 PK)
ORDER BY PK

From MSDN ORDER BY

When ORDER BY is used in the definition of a view, inline function, derived table, or subquery, the clause is used only to determine the rows returned by the TOP clause. The ORDER BY clause does not guarantee ordered results when these constructs are queried, unless ORDER BY is also specified in the query itself.

Edit, after feedback and including Martin Smith's idea

select ...
from DetailA A
     JOIN
     TVPorTemptable T ON A.PK = T.PK
ORDER BY
  T.OrderByCOlumn

Upvotes: 1

Related Questions