0

我有一个数据库表,其中有一个名为 的列File Content和许多行。我需要的是为每一行的File Content列创建一个文本文件。

例子:

Sr.        File Name        File Content

1.         FN1              Hello
2.         FN2              Good Morning
3.         FN3              How are you?
4.         FN4              Where are you?

假设我有 4 行,那么应该创建 4 个文本文件(可能是我们想要的任何名称)

  1. File1.txt应该有文本“你好”。
  2. File2.txt应该有文本“早安”。
  3. File3.txt应该有文字“你好吗?” 在里面。
  4. File4.txt应该有文字“你在哪里?” 在里面
4

2 回答 2

2

这可以通过 SQL 服务器的 BCP OUT 语法来完成。

对于设置:只需确保您在服务器上具有 xp_cmdshell 执行权限。这可以从 master.sys.configurations 表中检查。还要更改与您的服务器或网络共享相对应的文件位置路径。我检查并能够生成 4 个文件,因为表中有 4 条记录。

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
于 2012-06-02T13:40:59.473 回答
2

虽然你说你说你需要在 TSQL 中这样做,但如果可能的话,我不会那样做。Ram 向您展示了一种解决方案,但它的缺点是您需要使用 xp_cmdshell 并且 SQL Server 服务帐户需要在您想要拥有文件的任何位置访问文件系统的权限。

My suggestion would be to write a script or small program in your preferred language (PowerShell, Perl, Python, C#, whatever) and use that instead. TSQL as a language is simply badly suited for manipulating files or handling anything outside the database. It is obviously possible (CLR procedures are another way), but you often run into problems with permissions, encodings and other issues that are much easier to deal with in an external language.

于 2012-06-02T14:16:57.260 回答