SQL Server: Select Top 0?

后端 未结 8 1609
谎友^
谎友^ 2020-12-17 07:37

We just came across this in an old production stored proc (there is a lot more going on in here, but this is in one leg of its logic). Why would someone ever select top 0 ro

相关标签:
8条回答
  • 2020-12-17 08:09

    Use this to create a temporary table where the collation of your DB and TEMPDB may differ.

    SELECT TOP(0) column INTO #temp FROM [mytable]
    

    Produces a temp table with same collation as my table. This then means

    SELECT * FROM #temp T INNER JOIN [mytable] M ON M.column=T.column
    

    Does not fail due to a collation error.

    0 讨论(0)
  • 2020-12-17 08:14

    By doing this, you have an empty resultset with all columns instead of no result. If the program using the stored procedure expects certain columns, it would crash otherwise.

    0 讨论(0)
  • 2020-12-17 08:17

    You could use this to grab the column names.

    0 讨论(0)
  • 2020-12-17 08:18

    I have mostly used it when creating temp tables from an existing DB table - without any data. The following is more reliable though than using top.

    SELECT * FROM <table_name> LIMIT 0;
    
    0 讨论(0)
  • 2020-12-17 08:23

    Let me provide an additional use:

    If you want a message printed in the output rather than in messages, you could use

    select top 0 0 'Your message here'

    instead of

    print 'Your message here'

    0 讨论(0)
  • 2020-12-17 08:25

    You can use this to check if your SQL syntax is correct without loading any data.

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