13

I am trying to export my SQL Server query results into a folder in .txt format (this is for an automated job)

I know the equivalent in MySQL works with INTO OUTFILE. Does anyone know the best way to do this in SQL Server 2008 Management Studio?

SELECT DISTINCT RTRIM (s1.SGMNTID) AS 'AccCode',RTRIM (s1.DSCRIPTN) AS 'CodeDesc', CASE
    WHEN  s1.SGMTNUMB = '1' THEN '1' 
    WHEN s1.SGMTNUMB = '2' THEN '2'
    WHEN s1.SGMTNUMB = '3' THEN '110'
    WHEN s1.SGMTNUMB = '4' THEN '4'
    WHEN s1.SGMTNUMB = '5' THEN '120'
    END AS 'AccountType_id',
CASE WHEN s1.SGMTNUMB = '2' 
THEN LEFT(s1.SGMNTID, 2)
ELSE 'DEFAULT'
END AS 'AccGroupName'

 FROM GL40200 s1

UNION 

SELECT  REPLACE ([ACTNUMBR_1]+'-'+ [ACTNUMBR_2]+'-'+ [ACTNUMBR_3]+'-'+[ACTNUMBR_4]+'-'+    [ACTNUMBR_5],' ', '') AS 'AccCode',
 '' AS 'CodeDesc',
 '0' AS 'AccountType_id',
 'Default' AS 'AccGroupName'
FROM GL00100 a

INTO OUTFILE 'C:\Users\srahmani\verian/myfilename.txt'
4

6 回答 6

20

您可以在 SSMS 应用程序中执行此操作,而不是在 SQL 中。

在工具栏中选择:

Query --> Results To --> Results To File

于 2013-12-16T20:27:10.607 回答
11

另一种方法是从命令行,使用 osql:

OSQL -S SERVERNAME -E -i thequeryfile.sql -o youroutputfile.txt

这可以从 BAT 文件中使用,并由 Windows 用户安排以进行身份​​验证。

于 2013-12-16T20:42:12.487 回答
7

您可以使用bcp 实用程序

要将结果集从 Transact-SQL 语句复制到数据文件,请使用 queryout 选项。以下示例将查询结果复制到 Contacts.txt 数据文件中。该示例假定您正在使用 Windows 身份验证,并且与您正在运行 bcp 命令的服务器实例建立了可信连接。在 Windows 命令提示符下,输入:

bcp "<your query here>" queryout Contacts.txt -c -T

您可以通过在 SQL 代理作业中直接调用作为操作系统命令来使用 BCP。

于 2013-12-16T20:27:18.243 回答
6

您可以使用 windows Powershell 执行查询并将其输出到文本文件

Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt

于 2014-12-08T14:30:08.990 回答
0

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

于 2014-06-16T18:34:01.353 回答
-4

这很简单,并且可以在其他查​​询中找到答案。对于那些正在查看此内容的人:

select entries from my_entries where id='42' INTO OUTFILE 'bishwas.txt';
于 2016-09-22T08:48:16.247 回答