SQL Server:如何将每行转储/提取到单独的文件中

时间:2013-07-18 13:09:08

标签: sql sql-server

我有一个业务要求是使用列PrimaryKey, A, B, C, D, E获取表并将每个表转储到如下文件:

filename:  Primarykey.txt
(row 1) A
(row 2) B
(row 3) C

等。

有没有一种很好的方法可以使用SQL Server 2008执行此操作,还是应该使用数据表编写C#程序?我使用的表中有大约200k行。

由于

2 个答案:

答案 0 :(得分:1)

以下链接包含一些以前的帖子和使用SSIS的可能解决方案的另一个链接。

你可能需要四处游戏,直到得到你想要的东西。

祝你好运。

Some clues here

SQL Server Forums - Create multiple files from SSIS

答案 1 :(得分:1)

使用xp_cmdshell

如果允许使用xp_cmdshell,您可以使用以下内容:

zero

使用sqlcmd

或者,您可以创建一系列语句来运行declare @path varchar(200) declare @schema varchar(100) declare @pk varchar(100) declare @sql varchar(2000) declare @cmd varchar(2500) set @path = 'C:\your\file\path\' declare rowz cursor for (select PrimaryKey from TableA) open rowz fetch next from rowz into @pk while @@FETCH_STATUS = 0 begin set @sql = 'select A, B, C, D, E from TableA where PrimaryKey = ''' + @pk + '''' set @cmd = 'bcp "' + @sql + '" queryout "' + @path + @pk + '.txt" -T -c -t\n' exec xp_cmdshell @cmd fetch next from rowz into @item end close rowz deallocate rowz 来创建单独的文件。

首先,创建一个临时表并添加一些样板条目:

sqlcmd

然后,使用我们需要的查询填充临时表:

create table #temp (tkey int, things varchar(max))
insert into #temp (tkey, things) values (0, 'SET NOCOUNT ON;
GO'),(2, ':out stdout')

接下来,查询临时表以获取生成的查询:

declare @dir varchar(250)
declare @sql varchar(5000)
declare @cmd varchar(5500)
declare @schema varchar(100)
declare @pk varchar(100)
set @schema = 'YourSchema'
declare rowz cursor for (select PrimaryKey from "YourSchema"..TableA)
open rowz
fetch next from rowz into @pk
while @@FETCH_STATUS = 0
begin
    set @dir = '"C:\your\file\path\'+@pk+'.txt"'
    set @sql = '
SELECT A +''
''+ B +''
''+ C +''
''+ D +''
''+ E
FROM "'+@schema+'"..TableA where PrimaryKey = '+@pk
    set @cmd = ':out '+@dir+@sql+'
GO'
    insert into #temp (tkey,things) values (1, @cmd)
    fetch next from rowz into @pk
end
close rowz
deallocate rowz

最后,将结果复制到一个文件,并在命令提示符下使用参数select things from #temp order by tkey 将此文件作为输入发送到sqlcmd.exe

-h -1
相关问题