Link to home
Create AccountLog in
Avatar of soozh
soozhFlag for Sweden

asked on

TSQL - Best way to sort data in table and return part of it?

Hello,

MS SQL 2008.

I have a table:
create table #Patients (
	PersonId int,
	Personnummer nvarchar(50), 
	Efternamn nvarchar(50),
	Förnamn nvarchar(50),
    Öga int,
	DiagnosId int,
	Diagnosdatum date,
	BehandlingId int,
	Behandlingsdatum date,
	rNumber integer )  ;

Open in new window


In a stored procedure it gets populated with say 1000 rows.

I then need to return 15 rows (a page of data displayed by a calling application) after the table is sorted after one of its columns.

For example the sort may be on DiagnosDatum, and the stored procedure should return rows 16 to 30 (page 2).

Is there a recommended way of doing this?  Can i update the rNumber column with the rows sort order first, and then select rows between 16 and 30 (for page 2)?

something like Update #patients set fNumber = (the sort order based upon the column and order).

As the sort column can be any column in the table i suspect that some dynamic sql may be need here.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.