I'm working with SQL Server 2005, and I'm trying to sort the results based on a user selected letter. Say the user selects 'D' to filter his results. I'd like to return the results starting from D followed by E, F, G...Z, A, B, C. What I'm getting is the results for the D entries at the top of the result set, followed by A, B, C, E...Z.
A solution comes to mind that would be very long and db intensive, by querying on 'like 'D', followed by like 'E', followed by like 'F', etc, but I'm sure that there is a much more efficient way to do this. Below is the code that I'm using now.
' where @.SortString = 'd' and @.Test is a temp Table
BEGIN
Insert into @.Test
Select CompanyName,ContactId, CompanyId
from vContacts where CompanyName like @.SortString +'%'
Order by CompanyName
Insert into @.Test
Select CompanyName,ContactId, CompanyId
from vContacts where CompanyName not like @.SortString +'%'
Order by CompanyName
END
Thanks in advance for your help
Code Snippet
SELECT
OrderSet = 1,
CompanyName,
ContactId,
CompanyId
FROM vContacts
WHERE CompanyName >= @.SortString
UNION
Select
2
CompanyName,
ContactId,
CompanyId
FROM vContacts
WHERE CompanyName < @.SortString
ORDER BY
OrderSet,
CompanyName
No comments:
Post a Comment