【问题标题】:SQL Server - Create text files from value stored in a rowSQL Server - 从存储在行中的值创建文本文件
【发布时间】:2012-12-05 17:09:30
【问题描述】:

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

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 中实现这一点?

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    试试这样的:-

    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
    

    【讨论】:

    • 我在使用 bcp 命令时收到此错误 - 错误 = [Microsoft][SQL Native Client]Named Pipes Provider: 无法打开与 SQL Server [53] 的连接。我已经厌倦了一切,但它不起作用,任何建议
    • 除了使用 bcp 实用程序之外的任何其他方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多