T-SQL returns specific row data and paging query randomly

Source: Internet
Author: User

The T-SQL language adds a lot of features than standard SQL, and in order to improve SQL Server performance, it is necessary to get a deep understanding of these two minor issues that are typically included in an interview.

First, it is a random return of 5 lines of information in a AdventureWorks person.address, which can be written as follows:

Select Top 5 * 
from
(
    select *,newid () as Randomid to
    person.address
) T
ORDER by T.randomid

The key is to invoke the random number generated by the built-in function newid () and sort, taking the first 5 lines.

Paging query, you need to query person.address sorted by city after the 第50-200 line, of course, can write a stored procedure to specifically query by parameters.

SELECT * FROM
(
    select *,row_number ()-RowNumber from
    person.address
) as T
WHERE T.rownumber BETWEEN and 200

The key is to use the Row_number () function, to calculate the current row in all query rows is ranked, and then filter the final results.

Summary: With some language features, although the binding platform, however, on a large platform, it does not matter, it is worth it.

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/database/SQLServer/

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.