SQL Rowcount vs Top

前端 未结 4 1941
礼貌的吻别
礼貌的吻别 2021-01-04 05:39

What is the difference between

Set Rowcount X

And

Select Top X *
From Z

in TSQL?

相关标签:
4条回答
  • 2021-01-04 05:51

    Top can do a few more things for you. For one, you can specify a percentage, instead of an integer. You can also handle situations where ties in column values occur.

    http://technet.microsoft.com/en-us/library/ms189463.aspx

    0 讨论(0)
  • 2021-01-04 05:55

    In older versions of SQL Server (2005 and earlier I am not sure about 2008) you could not use a variable in a top statement so:

    declare @rc int
    
    set @rc=10
    
    select top @rc * from myTable --Wont work
    
    set rowcount @rc
    select * from myTable --Will work
    
    0 讨论(0)
  • 2021-01-04 05:59

    2008 and above allows

    declare @rc int
    
    set @rc=10000
    
    select top (@rc) * from myTable --will now work
    

    but only if you use () this can be usefull to use hints like:

    OPTION ( OPTIMIZE FOR (@rc= 15) )
    

    at the end allowing to select everithing but optimize for a more common case

    0 讨论(0)
  • 2021-01-04 06:03

    The main difference is that top will only effect the query you are running while set rowcount will persist with the connection and apply to all queries executed within that connection.

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