Why use Select Top 100 Percent?

后端 未结 10 2313
花落未央
花落未央 2020-11-27 15:41

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

10条回答
  •  我在风中等你
    2020-11-27 16:05

    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...
    

提交回复
热议问题