Monday, January 21, 2008

Do You Believe in Search After Search ?

Well, I'm trying to figure out some new techologies like WPF, WCF or new features of SQL Server 2005.
What I needed in my project was to do a select where to get the first n elements in a list, or the last m...where I wanted "n" or "m" to be variables. So after very little strugle I come up with the query in a stored procedure like this:


....
SELECT IDOffice, IDTicket
FROM (
SELECT ROW_NUMBER() OVER (
ORDER BY
CASE when @WhatToGet = 1 THEN IDOffice END ASC,
CASE WHEN @WhatToGet = 2 THEN IDOffice END DESC) AS ROWID,
IdOffice,
IdTicket
FROM TheTable t
WHERE
t.IdTicketStatus = @IdTicketStatus and
dbo.uf_GetDay(t.Date) = dbo.uf_GetDay(getdate())
GROUP BY IDOffice
) tmp
where ROWID <= @MaxOffices
ORDER BY IDOffice





Using this where rowId < @MaxOffices is an idea that come to my mind from the database engines that don's implement select top

It was working and it won't have big performance issues as the DB it'll run on will be pretty small. However, there was something I didn't like in it...so I did some google research and I come up with :

SELECT * from ( -- just to order by offices
SELECT TOP (@MaxOffices)
IdOffice,
dbo.uf_ConvertFromAbsolutIdTicketToRelative(Max(IdTicket)) IdTicket
FROM
TheTable t
WHERE
t.IdTicketStatus = @IdTicketStatus
AND dbo.uf_GetDay(t.Date) = dbo.uf_GetDay(getdate())
GROUP BY IDOffice
ORDER BY
CASE when @WhatToGet = 1 THEN IDOffice END ASC,
CASE WHEN @WhatToGet = 2 THEN IDOffice END DESC
) tmp
ORDER BY IDTicketoffice

this looks nicer, I didnt' know SQL Server 2005 implements the SELECT TOP (@parameter). I'll take one more look at this query, when time allows (it never allows).

No comments: