TSQL TOP Usage

Source: Internet
Author: User
Tags rowcount

The first part: TSQL Top has two uses

1, limits the number of rows or total rows returned by the query result set.

When the top is used in conjunction with the ORDER BY clause, the result set is limited to the first n sorted rows, otherwise the first n rows are returned in undefined order.

2, limit the number of rows affected by the INSERT, UPDATE, MERGE, or DELETE statements.

Part Two: Discussion of the second usage of top

1, the sample code is as follows

Create Tabledbo. Financemonth (Monthnumint, Quantityint); withCte as(    Select 1  asMonthnum, -  asQuantityUnion  All    SelectMonthnum+1, quantity+ -     fromCTEwhereMonthnum< A)Insert  intodbo. FinancemonthSelect * fromCte

2, use set ROWCOUNT to limit the number of rows returned, but Ms does not recommend this way, "in future versions of SQL Server, using set ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements."

SET ROWCOUNT 2 Select *  from dbo. Financemonth-- equivalent to selecttop2* from Dbo. Financemonth

Cancel limit, specify set ROWCOUNT to 0

SET ROWCOUNT 0

3, use top to limit the number of rows affected by Delete, INSERT, and update, and the number or percentage following top must be enclosed in parentheses, otherwise an error occurs.

Delete Top(2) fromdbo. FinancemonthUpdate Top(2) dbo. FinancemonthSetQuantity=1Insert Top(2) intodbo. FinancemonthSelect *  fromDbo. Financemonth

TSQL TOP Usage

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.