What are the methods to export SQL queries to a .txt file?

What are the methods to export SQL queries to a .txt file?

You are at the right place to export SQL queries to a .txt file in 5 ways. Look out for the five methods such as

• SQL Server Management Studio

• BCP

• Import/Export Wizard

• PowerShell

• SQL Server Command Line

SQL Server Management Studio:

It is not necessary to depend only on wizard but you would have done it with the help of SSMS.

Step 1: Go to Tools and then select “option”.

Step 2: Move on to “Query results” and then tap on “SQL Server”. Choose “Result to file” simultaneously help to choose the place where you will be saving all the queries.

Step 3: Start creating the query and don’t forget to execute it. Enter the name and file type on the location of the output entry.

BCP:

BCP is none other than a bulky copy program where it stands with SQL. It is the one that takes responsibility to import or export SQL queries in default.

Code:
bcp "SELECT TOP 10[PatientEntityID],[NationalIDNumber],[DepartmentNode], FROM Patient2021CZT2.[HumanResources].[Patient] WITH (NOLOCK)" queryout c:\sql\bcpoutput.txt -c -T
Using bcpoutput.txt, you can export the query.

Use -c for data type operation

Use -T for connection trust

Import/Export Wizard:

Step 1:
Go to SQL Server Management Studio and then select “Database” to right-click on it. Select “Import/Export” and then choose “Tasks”.

Step 2: Select “Export data” and open “SQL Server Import and Export”. Now, assume the data source as Microsoft OLE DB Provider. Enter the connection and server name in detail.

Step 3: Go to the section “Destination” to select “Flat File Destination”. You were about to save the text file right so, enter the path and file name over there.

Step 4: Tap on the button “Next” and then select “Write a query to specify the data to transfer”. Enter the SQL server query and verify it by clicking Parse. Once you click “Run Immediately” it starts exporting SQL server query to the .txt file.

PowerShell:

Use the below command to export SQL query with the help of PowerShell:


Code:
Invoke-Sqlcmd -InputFile "C:\sql\sqlquery.sql" | Out-File -filePath "C:\sql\sqlqueryoutput.txt"
The invoke-sqlcmd here helps to get input from sqlquery.sql and stores in the output of sqlqueryoutput.txt

SQL Server Command Line:

Here, SQL server command line plays a bigger role just by performing task automation with the below command:

Code:
sqlcmd -i c:\sql\sqlquery.sql -o c:\sql\sqlqueryoutput.txt
With this command execution, you can find the result of sqlquery.sql in sqlqueryoutput.txt. Use a text file to export query of SQL file.
Author
kumkumsharma
Views
529
First release
Last update
Rating
0.00 star(s) 0 ratings

More resources from kumkumsharma

Top