Summary of common methods for SQL Server queries before N records _mssql

Source: Internet
Author: User
Tags sql server query

The examples in this article describe the common methods of SQL Server query for the first N records. Share to everyone for your reference. Specifically as follows:

SQL Server Query the first n records are the operations we often use, the following SQL Server query the first n records of the method is described in detail, if you are interested, may wish to see.

SQL Server queries top N records:

Because IDs may not be contiguous, you cannot use the method of obtaining a 10<id<20 record.

There are three ways to achieve this:

First, search 20 records, specify not including the first 10

Statement:

Copy Code code as follows:
Select top of * from TBL where ID. (select top ID from TBL)

Second, the search record generates temporary tables, and establishes the ID of the temporary table. Obtain the required data by means of a record of the 10<id<20 of the self-increasing ID
Statement:
Copy Code code as follows:
Select Identity (int,1,1) as id,* into #temp from TBL;
SELECT * from #temp where ID between 20

The second method is actually two statements, but you can let him execute it continuously, just like a statement to complete the task.

Third, the friends feel that the first method is too inefficient, after discussion, come to the second method:
Statement:

Copy Code code as follows:
Select Top * "from" (select Top * "Tblorder by id" as Tbl2 order by Tbl2.id DESC

I hope this article will help you with your SQL Server database program.

Related Article

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.