是否可以从 Sql Server 返回空行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5297348/
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 09:41:42  来源:igfitidea点击:

Is it possible to return empty row from Sql Server?

sqlsql-serversql-server-2005sql-server-2008

提问by RichardTheKiwi

Is this possible to return all columns in query as empty column (not null) or empty row, in case the actual query is returning no rows

是否可以将查询中的所有列作为空列(非空)或空行返回,以防实际查询不返回任何行

回答by RichardTheKiwi

Generally, if you must have an empty row returned..

通常,如果您必须返回一个空行..

If your original query is

如果您的原始查询是

select a,b,c from tbl

You can turn it into a subquery

你可以把它变成一个子查询

select t.a,t.b,t.c
from (select 1 as adummy) a
left join (
    select a,b,c from tbl  -- original query
) t on 1=1

Which ensures the query will always have a rowcount of at least one.

这确保查询的行数始终至少为 1。

回答by Philippe Grondier

If your objective is to return a query with no records, or with an empty recordset/dataset, the following should work without any previous knowledge on the original query:

如果您的目标是返回没有记录或空记录集/数据集的查询,则以下内容应该可以在不了解原始查询的情况下工作:

SELECT * FROM (myOriginalQuery) as mySelect WHERE 0 = 1

回答by Fandango68

Based on Richard's answer, you can use UNIONS to give you "something"...

根据理查德的回答,你可以使用 UNIONS 给你“一些东西”......

select t.a, t.b, t.c
from (select null AS a, null AS b, null AS c
       union ALL
      select a, b, c from tbl)   -- original query
     ) AS t 
on 1=1

The '1=1' is really what forces SQL to return something.

' 1=1' 实际上是强制 SQL 返回某些内容的原因。