Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

8 Ways to Export SQL Results To a Text File

$
0
0

Introduction

This article will show eight ways to export rows from a T-SQL query to a txt file.We will show the following options:

Shows results to a file in SQL Server Management Studio (SSMS) SQLCMD PowerShell Import/Export Wizard in SSMS SSIS Wizard (almost the same than the number 4, but we are using SSDT instead of SSMS to create the package). C# SSRS BCP Requirements

You need a SQL Server Installed with SSIS and SQL Server Data Tools (SSDT).

Getting Started

Let's look at each of the ways we can export the results of a query.

1. Show results to a file in SSMS

In the first option, we will configure SSMS to display the query results to a txt file. We will use the following script, named myscript.sql:

USE [AdventureWorks2016CTP3]
GO
SELECT TOP 5 [BusinessEntityID]
,[NationalIDNumber]
,[OrganizationNode]
,[OrganizationLevel]
FROM [HumanResources].[Employee]
GO

The result displayed in SQL Server Management Studio (SSMS) is the following:


8 Ways to Export SQL Results To a Text File

If you want to save the results in a txt file, you can do this in SSMS. Go to Tools>Options :


8 Ways to Export SQL Results To a Text File

Select the option Result to file:


8 Ways to Export SQL Results To a Text File

Create a query and execute the query. An option to specify the name and path will be displayed. We will call the results in a file named Results.rpt:


8 Ways to Export SQL Results To a Text File

The result saved are the following:


8 Ways to Export SQL Results To a Text File
2. SQLCMD

SQLCMD is the SQL Server Command Line utility. You can save the results in a file from here. This option is useful when you are using batch files to automate tasks.

Use the following command in the cmd:

sqlcmd -i c:\sql\myquery.sql -o c:\sql\myoutput.txt

The command used the myquery.sql file created before and the output is store to the file myoutput.txt:


8 Ways to Export SQL Results To a Text File
3. PowerShell

PowerShell is an extremely popular command line shell to automate tasks. We can export the SQL Server query results to a txt file by executing the following cmdlets:

Invoke-Sqlcmd -InputFile "C:\sql\myquery.sql" | Out-File -filePath "C:\sql\powershelloutput.txt"

Invoke-Sqlcmd will call the script myquery.sql created at the beginning of this article and store the results in a file named powershelloutput.txt. The results will be the following:


8 Ways to Export SQL Results To a Text File
4. Import/Export Wizard in SSMS

In SSMS, when you right click a database. There is an option to import or export data. Go to Tasks>Export Data:


8 Ways to Export SQL Results To a Text File

You will open the SQL Server Import and Export wizard:


8 Ways to Export SQL Results To a Text File

We will export from SQL Server to a Flat file. Select the Microsoft OLE DB Provider as the Data Source:


8 Ways to Export SQL Results To a Text File

Specify the Server name and the connection information if necessary:


8 Ways to Export SQL Results To a Text File

In Destination, select Flat File Destination and press browse to specify the file name and path:


8 Ways to Export SQL Results To a Text File

In this example, the flat file name will be exportwizard.txt:


8 Ways to Export SQL Results To a Text File

Once that you have the file name and path, press next:


8 Ways to Export SQL Results To a Text File

Select the option "Write a query to specify the data to transfer":


8 Ways to Export SQL Results To a Text File

Specify the query of the file myquery.sql (used in other methods) and press parse to verify that the query is OK. A message specifying that the statement is valid should be displayed:


8 Ways to Export SQL Results To a Text File

Keep the default values:


8 Ways to Export SQL Results To a Text File

Select Run immediately to export the data immediately:


8 Ways to Export SQL Results To a Text File

The file created will be similar to this one:


8 Ways to Export SQL Results To a Text File
5. SSIS in SSDT

You can also use SSIS in SSDT. This method is similar to the Import/Export Wizard in SSMS, because SSMS calls SSIS to import and export Data.

Go to SSDT and then go to File>New Project and select Integration Services Project:


8 Ways to Export SQL Results To a Text File

In Solution Explorer, right click SSIS Packages and select SSIS Import and Export Wizard:


8 Ways to Export SQL Results To a Text File

The next steps are the same than in SSMS when we call the Import/Export wizard, but at the end, you do not have the option to run immediately.

To run the package, press Start:


8 Ways to Export SQL Results To a Text File

The package will generate a text file with the CSV format.

6. C#

You can export from SQL Server to a text file using C#. You could also perform a similar task using Visual Basic. In this example, we will use the Script task included in SSDT. This option is very useful if you are writing code and you need to integrate this task to the code.

To do this, in SSDT, drag and drop the Script Task:


8 Ways to Export SQL Results To a Text File

Double click Script Task and press the Edit Script button:


8 Ways to Export SQL Results To a Text File

In #region Namespaces add System.IO and Data.SqlClient . Sysem.IO is used to write information to a file (in this scenario a txt file) and Data.SqlClient is used to connect to SQL Server:


8 Ways to Export SQL Results To a Text File

In the Script in the region where is says add your code here, add the following code:

// TODO: Add your code here
string query = "SELECT TOP 5 [BusinessEntityID],[NationalIDNumber],[OrganizationNode],[OrganizationLevel] FROM [HumanResources].[Employee]";
string connectionSql = "Server=(local);Database=AdventureWorks2016CTP3;Integrated Security=true";
StreamWriter myFile = new StreamWriter(@"c:\sql\fileCSharp.txt");
using (SqlConnection connection = new SqlConnection(connectionSql))
{
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
myFile.WriteLine(String.Format("{0}, {1}, {2}, {3}",
reader["Busine

Viewing all articles
Browse latest Browse all 3160

Trending Articles