Using case statement in ROW_NUMBER() OVER ( ORDER BY ) causes severe performance issues
I have two queries the first one runs in 5 seconds, the second one takes a couple of minutes to run. I am trying to sort using a value passed to a stored procedure. Kindly let me know how I can fix this issue.
ONE
select top(10) ROW_NUMBER() OVER (
ORDER BY POData.PurchaseOrderNumber
) AS ROW_NUM,
Received.QuantityReceived,POData.PurchaseOrderNumber,POData.*
from POData inner join Received on POData.Id = Received.PODataId
TWO
declare @OrderBy nvarchar(32) = 'PurchaseOrderNumber'
select top(10)
ROW_NUMBER() OVER (
ORDER BY
case when @OrderBy = 'PurchaseOrderNumber' then POData.PurchaseOrderNumber end
) AS ROW_NUM,
Received.QuantityReceived,POData.*
from POData inner join Received on POData.Id = Received.PODataId