1

列を持つテーブルを取得し、PrimaryKey, A, B, C, D, Eそれぞれを次のようなファイルにダンプするというビジネス要件があります。

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

SQL Server 2008 でこれを行う良い方法はありますか、それともデータテーブルを使用して C# プログラムを作成する必要がありますか? 私が使用しているテーブルには、約20万行あります。

ありがとう

4

2 に答える 2

1

xp_cmdshell の使用

xp_cmdshell が許可されている場合、次のようなものを使用できる場合があります。

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 の使用

または、実行する一連のステートメントを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

C:\your\file\path>sqlcmd -h -1 -S YourServer -i "script.sql"
于 2016-03-19T18:44:52.110 に答える
1

以下のリンクには、以前の投稿と、SSIS を使用した解決策への別のリンクが含まれています。

必要なものが得られるまで、いじる必要があるかもしれません。

幸運を。

ここにいくつかの手がかりがあります

または SQL Server フォーラム - SSIS から複数のファイルを作成する

于 2013-07-18T13:19:47.267 に答える