SQL problem: the previous or next record of the record with the primary key ID and sorting condition is known.

Source: Internet
Author: User

Set the record ID to @ ID

The above record is:
Select top 1 * From Table1 where sorting field <(select
Sort field from Table1 where id = @ ID) order by sort field DESC
The following record is:
Select top 1 *
From Table1 where sorting field> (select sorting field from Table1 where id = @ ID) order by sorting Field

======================================
What does it mean to not use a record set? Is a result not a result set, but a value to a variable?

With a single record set, won't you store it into variables? The format is as follows:
The above record is:
Set @ idpre = (
Select top 1
ID from Table1 where sorting field <(select sorting field from Table1 where id = @ ID) order
Sort field DESC
)
The ID of the next record is:
Set @ idpre = (
Select top 1 ID from Table1
Where sorting field> (select sorting field from Table1 where id = @ ID) order by sorting Field
)

======================================
Good question!
Set the sorting fields to field1 int and field2 in sequence.
Varchar (30) field3 datetime
Set @ idpre = (
Select top 1 ID from Table1

Where
(Convert (varchar (10000000000 + field1) + space (30-len (field2) + field2, convert (varchar, field3, 120 ))

>
(Select
Sort field = (convert (varchar (10000000000 + field1) + space (30-len (field2) + field2, convert (varchar, field3, 120 ))

From Table1 where id = @ ID)
Order by sorting Field

-- The key is to convert all the sorted fields into varchar of a fixed length and then combine them together.
======================================

The requirement is not simple. Of course, it is no more simple. In fact, this statement is not very long and the logic is not very complex.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.