Máy chủ sql 100 phần trăm hàng đầu năm 2022

89

New! Save questions or answers and organize your favorite content.
Learn more.

I understand that prior to SQL Server 2005, you could "trick" SQL Server to allow use of an order by in a view definition, by also include TOP 100 PERCENT in the SELECT clause. But I have seen other code which I have inherited which uses SELECT TOP 100 PERCENT ... within dynamic SQL statements [used in ADO in ASP.NET apps, etc]. Is there any reason for this? Isn't the result the same as not including the TOP 100 PERCENT?

asked Oct 26, 2009 at 2:49

3

It was used for "intermediate materialization [Google search]"

Good article: Adam Machanic: Exploring the secrets of intermediate materialization

He even raised an MS Connect so it can be done in a cleaner fashion

My view is "not inherently bad", but don't use it unless 100% sure. The problem is, it works only at the time you do it and probably not later [patch level, schema, index, row counts etc]...

Worked example

This may fail because you don't know in which order things are evaluated

SELECT foo From MyTable WHERE ISNUMERIC [foo] = 1 AND CAST[foo AS int] > 100

And this may also fail because

SELECT foo
FROM
    [SELECT foo From MyTable WHERE ISNUMERIC [foo] = 1] bar
WHERE
    CAST[foo AS int] > 100

However, this did not in SQL Server 2000. The inner query is evaluated and spooled:

SELECT foo
FROM
    [SELECT TOP 100 PERCENT foo From MyTable WHERE ISNUMERIC [foo] = 1 ORDER BY foo] bar
WHERE
    CAST[foo AS int] > 100

Note, this still works in SQL Server 2005

SELECT TOP 2000000000 ... ORDER BY...

Diado

2,1993 gold badges18 silver badges21 bronze badges

answered Oct 26, 2009 at 5:34

gbngbn

413k80 gold badges574 silver badges663 bronze badges

2

TOP [100] PERCENT is completely meaningless in recent versions of SQL Server, and it [along with the corresponding ORDER BY, in the case of a view definition or derived table] is ignored by the query processor.

You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable. Sadly, some of Microsoft's graphical tools put this meaningless clause in.

As for why this might appear in dynamic SQL, I have no idea. You're correct that there's no reason for it, and the result is the same without it [and again, in the case of a view definition or derived table, without both the TOP and ORDER BY clauses].

answered Oct 26, 2009 at 3:38

Steve KassSteve Kass

7,04419 silver badges26 bronze badges

6

...allow use of an ORDER BY in a view definition.

That's not a good idea. A view should never have an ORDER BY defined.

An ORDER BY has an impact on performance - using it a view means that the ORDER BY will turn up in the explain plan. If you have a query where the view is joined to anything in the immediate query, or referenced in an inline view [CTE/subquery factoring] - the ORDER BY is always run prior to the final ORDER BY [assuming it was defined]. There's no benefit to ordering rows that aren't the final result set when the query isn't using TOP [or LIMIT for MySQL/Postgres].

Consider:

CREATE VIEW my_view AS
    SELECT i.item_id,
           i.item_description,
           it.item_type_description
      FROM ITEMS i
      JOIN ITEM_TYPES it ON it.item_type_id = i.item_type_id
  ORDER BY i.item_description

...

  SELECT t.item_id,
         t.item_description,
         t.item_type_description
    FROM my_view t
ORDER BY t.item_type_description

...is the equivalent to using:

  SELECT t.item_id,
         t.item_description,
         t.item_type_description
    FROM [SELECT i.item_id,
                 i.item_description,
                 it.item_type_description
            FROM ITEMS i
            JOIN ITEM_TYPES it ON it.item_type_id = i.item_type_id
        ORDER BY i.item_description] t
ORDER BY t.item_type_description

This is bad because:

  1. The example is ordering the list initially by the item description, and then it's reordered based on the item type description. It's wasted resources in the first sort - running as is does not mean it's running: ORDER BY item_type_description, item_description
  2. It's not obvious what the view is ordered by due to encapsulation. This does not mean you should create multiple views with different sort orders...

answered Oct 26, 2009 at 3:14

OMG PoniesOMG Ponies

318k79 gold badges511 silver badges494 bronze badges

0

If there is no ORDER BY clause, then TOP 100 PERCENT is redundant. [As you mention, this was the 'trick' with views]

[Hopefully the optimizer will optimize this away.]

answered Oct 26, 2009 at 2:53

Mitch WheatMitch Wheat

291k42 gold badges459 silver badges534 bronze badges

I have seen other code which I have inherited which uses SELECT TOP 100 PERCENT

The reason for this is simple: Enterprise Manager used to try to be helpful and format your code to include this for you. There was no point ever trying to remove it as it didn't really hurt anything and the next time you went to change it EM would insert it again.

answered Oct 26, 2009 at 3:12

Joel CoehoornJoel Coehoorn

386k110 gold badges558 silver badges786 bronze badges

No reason but indifference, I'd guess.

Such query strings are usually generated by a graphical query tool. The user joins a few tables, adds a filter, a sort order, and tests the results. Since the user may want to save the query as a view, the tool adds a TOP 100 PERCENT. In this case, though, the user copies the SQL into his code, parameterized the WHERE clause, and hides everything in a data access layer. Out of mind, out of sight.

answered Oct 26, 2009 at 3:03

Peter RadocchiaPeter Radocchia

10.5k1 gold badge33 silver badges55 bronze badges

Kindly try the below, Hope it will work for you.

      SELECT TOP
              [ SELECT COUNT[foo] 
                  From MyTable 
                 WHERE ISNUMERIC [foo] = 1] * 
                  FROM bar WITH[NOLOCK] 
              ORDER BY foo
                 WHERE CAST[foo AS int] > 100
               ]

answered Mar 26, 2015 at 10:36

The error says it all...

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Don't use TOP 100 PERCENT, use TOP n, where N is a number

The TOP 100 PERCENT [for reasons I don't know] is ignored by SQL Server VIEW [post 2012 versions], but I think MS kept it for syntax reasons. TOP n is better and will work inside a view and sort it the way you want when a view is used initially, but be careful.

answered Mar 11, 2019 at 3:34

Fandango68Fandango68

4,1093 gold badges36 silver badges66 bronze badges

I would suppose that you can use a variable in the result, but aside from getting the ORDER BY piece in a view, you will not see a benefit by implicitly stating "TOP 100 PERCENT":

declare @t int
set @t=100
select top [@t] percent * from tableOf

answered Nov 18, 2014 at 17:41

1

Just try this, it explains it pretty much itself. You can't create a view with an ORDER BY except if...

CREATE VIEW v_Test
         AS
           SELECT name
             FROM sysobjects
         ORDER BY name
        GO

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

answered Jun 12, 2018 at 10:13

Trong bài viết này, chúng tôi sẽ tìm hiểu cách sử dụng các truy vấn hàng đầu của SQL chọn và chúng tôi cũng sẽ củng cố việc học này bằng các ví dụ.

Giới thiệu

Mệnh đề hàng đầu cho phép chúng tôi giới hạn tập hợp kết quả của các truy vấn theo số lượng hàng hoặc tỷ lệ phần trăm của các hàng. Nói chung, hàng đầu và trật tự bằng cách xây dựng được sử dụng cùng nhau. Nếu không, mệnh đề trên cùng sẽ trả lại số n của hàng theo thứ tự không chắc chắn. Vì lý do này, đó là cách thực hành tốt nhất để sử dụng mệnh đề hàng đầu với một đơn đặt hàng để có được một kết quả được sắp xếp nhất định.

Cú pháp của mệnh đề hàng đầu như sau:

SELECTTOP[expression][PERCENT]TOP[expression][PERCENT]

    [WITHTIES][WITHTIES]

TỪ

    table_nametable_name

Tranh luận

Biểu hiện

Biểu thức số này xác định có bao nhiêu hàng được trả về từ truy vấn. Chẳng hạn, khi chúng tôi muốn trả lại 10 hàng đầu tiên của bảng, chúng tôi có thể đặt tham số này là 10. Trong ví dụ này, chúng tôi lấy 5 hàng ngẫu nhiên từ bảng sản phẩm.

SELECTTOP[5]Name,TOP[5]Name,

    ProductNumber,ProductNumber,

    StandardCostStandardCost

FROMProduction.Product;Production.Product;

PHẦN TRĂM

Phần trăm từ khóa chỉ định rằng truy vấn sẽ trả về các hàng theo tỷ lệ %N của tập kết quả. Giá trị này phải nằm trong khoảng từ 0 đến 100. chẳng hạn như, nếu chúng ta muốn lấy một nửa các hàng trong bảng, sẽ đủ để đặt giá trị này thành 50. Truy vấn sau sẽ trả lại 20 phần trăm hàng trong bảng.

SELECTTOP[20]PERCENTName,TOP[20]PERCENTName,

    ProductNumber,ProductNumber,

    StandardCostStandardCost

FROMProduction.Product;Production.Product;

Với mối quan hệ

Từ khóa có TIES cho phép đưa các hàng vào tập kết quả khớp với hàng cuối cùng. Chúng ta cần tính đến một điểm về các mối quan hệ, việc sử dụng biểu thức này trong các truy vấn có thể khiến nhiều hàng được trả về hơn chúng ta chỉ định trong biểu thức trên cùng. Ví dụ: nếu chúng ta muốn truy xuất sản phẩm có chi phí cao nhất, chúng ta có thể sử dụng từ khóa Top 1. Tuy nhiên, nếu chúng ta thêm từ khóa có mối quan hệ vào câu lệnh TOP SQL Chọn, truy vấn sẽ trả về tất cả các hàng có cùng chi phí. Với TIES từ khóa phải được sử dụng với thứ tự bằng. Hãy để thực hiện các truy vấn sau và sau đó giải thích kết quả.WITH TIES keyword enables to include the rows into the result set that matches with the last row. We need to take into account one point about the WITH TIES, usage of this expression in the queries may cause more rows to be returned than we specify in the TOP expression. For example, if we want to retrieve the highest cost product we can use the TOP 1 keyword. However, if we add the WITH TIES keyword to the SQL SELECT TOP statement, the query will return all rows which have the same cost. WITH TIES keyword must be used with the ORDER BY. Let’s execute the following query and then interpret the result.

SELECTTOP[1]WITHTIESName,TOP[1]WITHTIESName,

    ProductNumber,ProductNumber,

    StandardCostStandardCost

FROMProduction.ProductProduction.Product

OrderByStandardCostdescBYStandardCostDESC

Như chúng ta có thể thấy, truy vấn đã trả lại nhiều hơn một sản phẩm có chi phí giống như sản phẩm đầu tiên.

Sử dụng câu lệnh SQL Chọn hàng đầu với một biến

Các biến là các đối tượng cơ sở dữ liệu được sử dụng để lưu trữ dữ liệu trong quá trình thực hiện truy vấn. Trong truy vấn sau, chúng tôi gán một giá trị cho biến và truy vấn sẽ trả về các hàng đầu tiên bằng giá trị được gán biến.

equalthevariableassignedvalue.thevariableassignedvalue.

DECLARE@ValASINT@ValASINT

SET@Val=3@Val=3

SelectTop [@val] & nbsp; & nbsp; Tên, TOP[@Val]   Name,

        ProductNumber,ProductNumber,

        StandardCostStandardCost

FROMProduction.ProductProduction.Product

OrderByStandardCostdesc BYStandardCostDESC

  • Như chúng ta có thể thấy, truy vấn đã trả lại nhiều hơn một sản phẩm có chi phí giống như sản phẩm đầu tiên.The TOP clause accepts 0 to bigint [9223372036854775807] as an argument. For example, the following query will return an error because the argument is bigger than the maximum value of the bigint

Sử dụng câu lệnh SQL Chọn hàng đầu với một biếnTOP[9223372036854775808]   Name,

    ProductNumber,ProductNumber,

    StandardCostStandardCost

FROMProduction.ProductProduction.Product

OrderByStandardCostdesc BYStandardCostDESC

Như chúng ta có thể thấy, truy vấn đã trả lại nhiều hơn một sản phẩm có chi phí giống như sản phẩm đầu tiên.

Sử dụng câu lệnh SQL Chọn hàng đầu với một biến

Các biến là các đối tượng cơ sở dữ liệu được sử dụng để lưu trữ dữ liệu trong quá trình thực hiện truy vấn. Trong truy vấn sau, chúng tôi gán một giá trị cho biến và truy vấn sẽ trả về các hàng đầu tiên bằng giá trị được gán biến.

UPDATETOP[10]Production.ProductListColors        TOP[10]Production.ProductListColors        

SETColor  ='Pink'Color  ='Pink'

SelectTop [@val] & nbsp; & nbsp; Tên,

UPDATETOP[50]  PERCENTProduction.ProductListColors        TOP[50]  PERCENTProduction.ProductListColors        

SETColor  ='Pink'Color  ='Pink'

Mẹo: Mệnh đề hàng đầu chấp nhận 0 đến Bigint [9223372036854775807] như một đối số. Ví dụ: truy vấn sau sẽ trả về lỗi vì đối số lớn hơn giá trị tối đa của Bigint

SelectTop [9223372036854775808] & nbsp; & nbsp; Tên,table.

DELETETOP[1]TOP[1]

FROMProduction.ProductListColors;Production.ProductListColors;

Như đã được chỉ ra trong hình ảnh trên, truy vấn đã trả về một lỗi tràn số học.

WITHDelCTEAS[DelCTEAS[

SELECTTOP1*FROMProduction.ProductListColorsTOP1*FROMProduction.ProductListColors

ORDERBYProductIDDESC]BYProductIDDESC]

Sử dụng câu lệnh hàng đầu cập nhật SQL FROMDelCTE

Khi chúng tôi sử dụng mệnh đề hàng đầu với câu lệnh cập nhật, bản cập nhật sẽ chạy cho các hàng không xác định vì chúng tôi không thể thêm thứ tự bằng loại câu lệnh cập nhật này. Các truy vấn dưới đây cho thấy loại sử dụng này.

Đặt tùy chọn RowCount giới hạn số lượng hàng trả về từ truy vấn. Khi chúng tôi đặt Set RowCount thành 4 cho truy vấn sau, nó sẽ xử lý toàn bộ truy vấn nhưng chỉ trả về 4 hàng.

SETROWCOUNT  4ROWCOUNT  4

Chọn & nbsp; & nbsp; Tên,   Name,

        ProductNumber,ProductNumber,

        StandardCostStandardCost

  FROMProduction.ProductFROM Production.Product

Đặt tùy chọn RowCount ghi đè từ khóa trên cùng, nếu giá trị đặt của RowCount nhỏ hơn biểu thức trên cùng, số lượng hàng được trả về sẽ bằng tùy chọn RowCount. Ví dụ: truy vấn sau sẽ chỉ trả về 2 hàng.

SETROWCOUNT  2ROWCOUNT  2

SELECT  TOP[5]Name,  TOP[5]Name,

            ProductNumber,ProductNumber,

            StandardCostStandardCost

  FROMProduction.ProductFROMProduction.Product

Sự khác biệt chính giữa câu lệnh hàng đầu chọn SQL và SET & NBSP; Tùy chọn RowCount là SET & NBSP; Tùy chọn RowCount không xem xét bởi trình tối ưu hóa truy vấn và hiệu suất của nó có thể tồi tệ hơn mệnh đề hàng đầu. Mặc dù vậy, các điều khoản hàng đầu tham gia vào các kế hoạch truy vấn của các truy vấn.

SQL CHỌN câu lệnh TOP so với chức năng Row_Number

Hàm Row_Number giúp cung cấp các số tạm thời cho tập hợp kết quả của truy vấn và nó cũng có thể được sử dụng thay vì các mệnh đề hàng đầu. Ví dụ: truy vấn sau sẽ trả về 4 hàng đầu tiên của bảng sản phẩm.

SELECT*FROM[*FROM[

SELECTName,Name,

        ProductNumber,ProductNumber,

        StandardCost,StandardCost,

        ROW_NUMBER[]OVER[ORDERBYStandardCostDESC]ASRNROW_NUMBER[] OVER[ORDERBYStandardCostDESC]ASRN

FROMProduction.ProductProduction.Product

]ASTMP_TBLASTMP_TBL

Ở đâuRN

Chủ Đề