TOP versus SET ROWCOUNT

前端 未结 2 573
半阙折子戏
半阙折子戏 2020-12-18 22:15

Is there a difference in performance between TOP and SET ROWCOUNT or do they just get executed in the same manner?

相关标签:
2条回答
  • 2020-12-18 22:53

    Yes, functionally they are the same thing. As far as I know there are no significant performance differences between the two.

    Just one thing to note is that once you have set rowcount this will persist for the life of the connection so make sure you reset it to 0 once you are done with it.


    EDIT (post Martin's comment)

    The scope of SET ROWCOUNT is for the current procedure only. This includes procedures called by the current procedure. It also includes dynamic SQL executed via EXEC or SP_EXECUTESQL since they are considered "child" scopes.

    Notice that SET ROWCOUNT is in a BEGIN/END scope, but it extends beyond that.

    create proc test1
    as
    begin
        begin
        set rowcount 100
        end
        exec ('select top 101 * from master..spt_values')
    end
    GO
    
    exec test1
    select top 102 * from master..spt_values
    

    Result = 100 rows, then 102 rows

    0 讨论(0)
  • 2020-12-18 22:53

    One more note about performance, according to BOL:

    As a part of a SELECT statement, the query optimizer can consider the value of expression in the TOP or FETCH clauses during query optimization. Because SET ROWCOUNT is used outside a statement that executes a query, its value cannot be considered in a query plan.

    Article on BOL

    Meaning there might be actually performance difference in these.

    0 讨论(0)
提交回复
热议问题