Problem solve Get help with specific problems with your technologies, process and projects.

The "next" composite primary key

Using SQL v 8.00, I would like to write a generic SQL statement that will find the "next record" (based on whatever ORDER BY clause you specify) from the given key when there is a composite primary key.

Example: Here's my table with two columns:

itemId locId
 I01     1
 I01     4
 I01    10
 I2      1
 I2      4

Is it possible to write one generic SQL statement that will return the "next" row (i.e. one row in my result set) when my key is ('I01',4)? It should return ('I01',10). I've tried to concatenate the fields, but have problems with left justified integers. Is this possible without using a cursor?

Everything in a relational database is possible without cursors. Thanks for asking.

Okay, some things are more efficient with a cursor, but those are exceedingly rare. <grin />

You said "SQL v 8.00" which presumably is Microsoft SQL Server, so here's a solution that will work for that particular database system:

declare @searchItem varchar(9)
declare @searchLoc integer

set @searchItem ='I01'
set @searchLoc  =4

select top 1
       itemId, locId
  from yourtable
 where itemid > @searchItem
    or (
       itemid = @searchItem
   and locID  > @searchLoc
    by itemId, locId

itemId locId

 I01    10   

This isn't strictly "generic" SQL, since it uses the Microsoft-specific TOP keyword.

For More Information

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.