代码之家  ›  专栏  ›  技术社区  ›  Craig Schwarze

如何使用tsql将表输出到txt文件?

  •  4
  • Craig Schwarze  · 技术社区  · 14 年前

    如何使用tsql将表输出到txt文件?我不想在此实例中使用DTS或SSI。

    4 回复  |  直到 14 年前
        1
  •  5
  •   Paul Creasey    14 年前

    BCP

    bcp MyDb.MySchema.Mytable out myTable.dat -T -c
    
    • 可替换为 询问 在里面
    • -T windows身份验证,替换为-u和-p表示sql身份验证
    • -c输出为文本而不是二进制
    • -r是行终止符选项
    • -S以指定非默认服务器

    我想这就是所有真正有用的出口选择。

        2
  •  5
  •   Anthony    14 年前

    以下是谷歌搜索中最常见的答案:

    EXEC master..xp_cmdshell'bcp "SELECT TOP 5 CUSTOMERID FROM Northwind.dbo.Customers" queryout "c:\text.txt" -c -T -x'
    
        3
  •  4
  •   Rubens Farias    14 年前

    您也可以按 + F SQL Server Management Studio 输出到文件。

        4
  •  2
  •   Graeme    11 年前

    我一直使用SQLCMD模式来执行此操作。以下是一个例子:

    -----------------------------
    --Generate State seeds
    -----------------------------
    
    -- This is the path and file where you want the scripts to land.
    :setvar OutDir "C:\Dev\Sandbox\GenTest\Scripts\"
    :setvar OutFile "dbo.State.seed.sql" 
    
    SET NOCOUNT ON;
    GO
    
    :out $(OutDir)$(OutFile)
    
    SELECT 
        'INSERT [State] ([StateId], [StateCd], [Description]) VALUES ('
        + CAST( [StateId] AS VARCHAR(2))
        + ', ''' + [StateCd] + ''''
        + ', ''' + [Description] + ''''
        + ');'
    FROM [State];
    
    GO  --this 'GO' is vital for this to work correctly.
    
    :out stdout