我可以使用t-sql这样的select语句来选择和提取记录列表:
select * from [dbo].[testTable];
但是如何将“自定义”行添加到结果集的顶部?
例如,如果结果集是:
John john@email.com
Max max@domain.com
我想在表格中添加一行,而不是从表中添加一行,以便它看起来像这样:
Name Email
John john@email.com
Max max@domain.com
我之所以这样做是因为我要通过sqlcmd将其导出到csv文件中,我想将这些“自定义行”添加为标题。
答案 0 :(得分:8)
这是安全的方法:
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
将起作用:
select 'name' as name, 'email' as email
union all
select name, email from [dbo].[testTable]
但是,我找不到保证第一个子查询在第二个子查询之前完成的文档。 SQL Server 中的基础操作符具有此行为(或者至少在我上次调查时在SQL Server 2008中执行过此操作)。
答案 1 :(得分:4)
SELECT name, email FROM (
SELECT 'Name' AS Name, 'Email' AS Email, 1 AS o
UNION ALL
SELECT name, email, 2 AS o FROM testTable
) t
ORDER BY o, name
添加o列以对UNION的结果集进行排序,以确保第一个结果集显示在顶部。
答案 2 :(得分:0)
SELECT * FROM
(SELECT 'Name' as name, 'Email' as email, 1 'rank'
union
SELECT name, email,3 'rank')a
ORDER BY a.rank,a.name
尝试以上方法。