SQL Server - 从存储在一行中的值创建文本文件

时间:2012-12-05 17:09:30

标签: sql-server

我有一个有一个字段的表(信息)。

Information
===========
Hello World 1
This is testing message
How are  you

我想创建三个文本文件(行数为3),其中的内容将基于行中的值。

所以,

  • File1.txt将有Hello World 1
  • File2.txt将有This is testing message

我们如何在SQL Server中实现这一目标?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情: -

use master
go

declare @DSQL Nvarchar(max)
declare @counter int
declare @maxrows int
declare @filename Nvarchar(30)

select @counter=1, @maxrows = 0

create table t1 (
 sno int identity(1,1) not null,
 filename varchar(5),
 filecontent varchar(100)
)

insert into t1
select 'FN1', 'Hello'
UNION
select 'FN2', 'Good Morning'
UNION
select 'FN3', 'How are you?'
UNION
select 'FN14', 'Where are you?'

select @maxrows = count(*) from t1

--SELECT * FROM T1

while (@counter <= @maxrows)
begin
  select @filename = filename from t1
   where sno = @counter
select @DSQL = N'exec xp_cmdshell' + ' ''bcp "select filecontent from master.dbo.T1 where sno = ' + cast(@counter as nvarchar(10)) + '" queryout "d:\temp\' + @filename + '.txt" -T -c -S home-e93994b54f'''

print @dsql
exec sp_executesql @DSQL
   select @counter = @counter + 1
end

drop table t1