使用bcp实用程序和SQL Server 2008将导出表转换为带有列标题(列名)的文件 [英] export table to file with column headers (column names) using the bcp utility and SQL Server 2008

查看:1660
本文介绍了使用bcp实用程序和SQL Server 2008将导出表转换为带有列标题(列名)的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一些黑客试图让bcp实用程序导出列名称和数据。如果我所做的是将一个表转储到一个文本文件最直接的方法是什么是bcp添加列标题?

I have seen a number of hacks to try to get the bcp utility to export column names along with the data. If all I am doing is dumping a table to a text file what is the most straightforward method to have bcp add the column headers?

这里是我目前使用的bcp命令:

Here's the bcp command I am currently using:

bcp myschema.dbo.myTableout myTable.csv /SmyServer01 /c /t, -T


推荐答案

最简单的是使用 queryout 选项并使用 union all 将列列表与实际表内容链接

The easiest is to use the queryout option and use union all to link a column list with the actual table content

    bcp "select 'col1', 'col2',... union all select * from myschema.dbo.myTableout" queryout myTable.csv /SmyServer01 /c /t, -T

例如:

create table Question1355876 
(id int, name varchar(10), someinfo numeric)

insert into Question1355876 
values (1, 'a', 123.12)
     , (2, 'b', 456.78)
     , (3, 'c', 901.12)
     , (4, 'd', 353.76)

此查询将返回头信息作为第一行。 (注意数值的转换)

This query will return the information with the headers as first row. (Note the casts of the numeric values)

select 'col1', 'col2', 'col3'
union all
select cast(id as varchar(10)), name, cast(someinfo as varchar(28))
from Question1355876

bcp命令将是:

bcp "select 'col1', 'col2', 'col3' union all select cast(id as varchar(10)), name, cast(someinfo as varchar(28)) from Question1355876" queryout myTable.csv /SmyServer01 /c /t, -T

这篇关于使用bcp实用程序和SQL Server 2008将导出表转换为带有列标题(列名)的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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