dbTalk Databases Forums  

SQL Pagination With Dynamic Order By

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss SQL Pagination With Dynamic Order By in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
rmturner76@gmail.com
 
Posts: n/a

Default SQL Pagination With Dynamic Order By - 04-04-2007 , 10:26 AM






I have a need to perform pagination while using dynamic sorting. As
an exmaple -

SELECT TOP(10) * FROM (
SELECT
TextColumn,
DecimalColumn,
ROW_NUMER() OVER (
ORDER BY
CASE @x
WHEN 1 THEN TextColumn
WHEN 2 THEN DecimalColumn
END
DESC
) AS SortOrder
FROM Table1
) AS Results WHERE SortOrder > ( 10 ) ORDER BY SortOrder

This is obviously just some sample but an error is given because the
data type of the 2 columns used in the order by are different. It
works if I cast DecimalColumn to match the textcolumn but then the
sorting is wrong. Is there a way to do this in a single query with 2
different data types?

Thanks for your help.


Reply With Quote
  #2  
Old   
Ed Murphy
 
Posts: n/a

Default Re: SQL Pagination With Dynamic Order By - 04-04-2007 , 10:52 AM






rmturner76 (AT) gmail (DOT) com wrote:

Quote:
I have a need to perform pagination while using dynamic sorting. As
an exmaple -

SELECT TOP(10) * FROM (
SELECT
TextColumn,
DecimalColumn,
ROW_NUMER() OVER (
ORDER BY
CASE @x
WHEN 1 THEN TextColumn
WHEN 2 THEN DecimalColumn
END
DESC
) AS SortOrder
FROM Table1
) AS Results WHERE SortOrder > ( 10 ) ORDER BY SortOrder

This is obviously just some sample but an error is given because the
data type of the 2 columns used in the order by are different. It
works if I cast DecimalColumn to match the textcolumn but then the
sorting is wrong. Is there a way to do this in a single query with 2
different data types?
Try this:

WHEN 2 THEN
right(' '+cast(DecimalColumn as varchar(20)), 20)


Reply With Quote
  #3  
Old   
--CELKO--
 
Posts: n/a

Default Re: SQL Pagination With Dynamic Order By - 04-04-2007 , 11:48 AM



Quote:
Is there a way to do this in a single query with 2 different data types?
The CASE expression has to have one and only one data type, just like
any other expression in SQL and strongly typed languages.

The trick is to keep both columns and NULL one of the out or make it a
constant, somethign like this:

ROW_NUMBER() OVER (ORDER BY
CASE WHEN @x = 1 THEN decimal_col ELSE CAST(NULL AS DECIMAL(s,p)) END,
CASE WHEN @x = 2 THEN text_col ELSE CAST (NULL AS CHAR(n)) END) AS
sort_order

The casting is a bit redundant, but a nice reminder.



Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.