如何添加“自定义"?行到选择结果集的顶部? [英] How can I add a "custom" row to the top of a select result set?

查看:23
本文介绍了如何添加“自定义"?行到选择结果集的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用像 t-sql 这样的 select 语句来选择和拉出记录列表:

I can select and pull out a list of records by using a select statement like so with t-sql:

select * from [dbo].[testTable];

但是如何将自定义"行添加到结果集的顶部?

But how can I add in a "custom" row to the top of the result set?

例如,如果结果集是:

John    john@email.com
Max     max@domain.com

我想在结果集中添加一行,它不是来自表中的,所以它看起来像这样:

I want to add a row, which is not from the table, to the result set so that it looks like so:

Name    Email
John    john@email.com
Max     max@domain.com

我之所以要这样做是因为我要通过 sqlcmd 将其导出到 csv 文件中,并且我想将这些自定义行"添加为标题.

The reason why I want to do this is because I'm going to export this into a csv file through sqlcmd and I want to add in those "custom row" as headers.

推荐答案

这是安全的方法:

select name, email
from ((select 'name' as name, 'email' as email, 1 as which
      ) union all
      (select name, email, 2 as which from [dbo].[testTable]
      )
     ) t
order by which;

在实践中,union all 会起作用:

In practice, union all will work:

      select 'name' as name, 'email' as email
      union all
      select name, email from [dbo].[testTable]

但是,我找不到保证第一个子查询在第二个子查询之前完成的文档.SQL Server 中的底层运算符确实具有这种行为(或者至少在我上次调查时在 SQL Server 2008 中具有这种行为).

However, I cannot find documentation that guarantees that the first subquery is completed before the second. The underlying operator in SQL Server does have this behavior (or at least it did in SQL Server 2008 when I last investigated it).

这篇关于如何添加“自定义"?行到选择结果集的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆