Set of records
Q: One of my tables contains a single-column primary key named Idvalue. For a given idvalue value, I want to find a table row immediately before and after the target value (assuming the results are sorted by idvalue). How do you get the results you need from a set based approach without using a cursor?
A: Transact-SQL is a collection based language, and it is not easy to use it to locate specific rows in the result set. However, server-side ANSI Transact-SQL cursors are far less performance than a collection based solution, so it is important to learn a variety of techniques to solve problems, especially when faced with these problems.
Take the Orders table in the Northwind database as an example. We can recapitulate the question: How can we find rows immediately before and after a particular row in the Orders table without using a cursor? Let's say we sort the result set according to the OrderID column.
Creative use of the Min (), MAX (), and top features of SQL Server can help you solve such result set positioning problems. Program Listings 1 and 2 give two similar, slightly different solutions. Listing 1 provides a common solution because it utilizes the @targetorder min () and Max () endpoints. In some cases, however, the flexibility of showing top is also useful. Note that when the minimum OrderID (10248) of the Orders table is supplied as a parameter, the query in Listing 2 returns the empty set because the query assumes that there is always a row before the @targetorder row.
Generally, there are more than one method of generating a result set, one of which is usually more efficient than the others. When you evaluate Showplan and set STATISTICS IO information for these two examples, you will find that the program listing 2, which uses the top statement, is slightly more efficient than listing 1. The difference is subtle because the sample dataset is small, but it is important to test the performance of different methods in the presence of multiple query methods.
-brian Moran
Listing 1: Finding the target row using the min () and MAX () function that contains the OR keyword
DECLARE @TargetOrder int
SET @TargetOrder =10330
From Orders
WHERE orderid= @TargetOrder
OR orderid= (SELECT MAX (OrderId)
From Orders WHERE OrderId < @TargetOrder)
OR OrderId = (SELECT MIN (OrderId)
From Orders WHERE OrderId > @TargetOrder)
Listing 2: Finding a target row using the top keyword
SELECT
Top 3
*
From Orders
WHERE OrderId >= (SELECT MAX (OrderId) from Orders
WHERE OrderId < @TargetOrder)
ORDER BY
OrderId