tags:

views:

17

answers:

1

Hi,

I have a query which has a paging functionality and for which i'm using ROW_NUMBER() function. The order by clause in my rownumber function is dynamic and gets changed all the time when ever the sp is called. It works fine for few columns but for one column which is of datetime datatype, it takes lot of time. Amazing thing is with when i sort by the same column in descending order, the query runs in a sec but ascending order takes lot of time :(.

I tried creating a non clustered index(as i already i have a clustered index on that table) on that datetime column but it did not help me.

Could you please suggest what i can do to improve the performance.

Thanks,

Deepti

+1  A: 

Assuming that this is SQL Server 2005 (I haven't checked 2008), the ROW_NUMBER() function is notorious for causing sensitivity issues in the SQL optimiser. Mr Google will show you numerous examples where a relatively small change such as sort direction causes the optimiser to create a very different execution plan.

Your best bet is to check the cached execution plans to see the differences:

SELECT sc.*
FROM master.dbo.syscacheobjects AS sc
WHERE sc.cacheobjtype = 'Executable Plan'

Alternatively you can change your approach and adapt something nifty like this.

RoadWarrior
Allegedly better in SQL Server 2008...
gbn