SQL Server:选择前 0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6033957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:36:05  来源:igfitidea点击:

SQL Server: Select Top 0?

sqlsql-serversql-server-2005

提问by Dave Ziegler

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 rows from a table? Is this some sort of SQL hack or trick I am not familiar with?

我们刚刚在旧的生产存储过程中遇到了这个问题(这里还有很多事情要做,但这只是其逻辑的一个方面)。为什么有人会从表中选择前 0 行?这是某种我不熟悉的 SQL hack 或技巧吗?

采纳答案by richard

To name columns in a UNION ALL

在 UNION ALL 中命名列

Be sure to read Alex K.'s answer as well. He has a lot of reasons that I have used as well. This was just the most obvious one.

请务必阅读 Alex K. 的回答。他有很多我也用过的理由。这只是最明显的一个。

回答by Alex K.

Its a way of getting an empty set; for example to create a new empty table with the same columns as an existing one;

它是一种获得空集的方法;例如,创建一个与现有表具有相同列的新空表;

SELECT TOP 0 * INTO new_table FROM old_table

Or to act a as source for column names
Or as a way to return column details but no data to a client layer
Or as a query to check connectivity

或者作为列名的来源
或者作为向客户层返回列详细信息但没有数据的方式
或者作为检查连接的查询

Its the same as;

它与;

SELECT * FROM table WHERE 0=1

回答by Mr47

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.

通过这样做,您将拥有一个包含所有列的空结果集,而不是没有结果。如果使用存储过程的程序需要某些列,否则它会崩溃。

回答by dtbarne

You could use this to grab the column names.

您可以使用它来获取列名。

回答by Tony M

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

使用它来创建一个临时表,其中您的 DB 和 TEMPDB 的排序规则可能不同。

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.

不会因整理错误而失败。

回答by George Menoutis

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'

select top 0 0 'Your message here'

instead of

代替

print 'Your message here'

print 'Your message here'

回答by Maninder Gill

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.

我主要在从现有数据库表创建临时表时使用它 - 没有任何数据。以下比使用 top 更可靠。

SELECT * FROM <table_name> LIMIT 0;