The "next" composite primary key

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?


    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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
       )
order
    by itemId, locId

itemId locId

 I01    10   

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

For More Information


This was first published in June 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.