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 ) 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
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, SQL Server, DB2, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
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.