There are several ways to export data in SQL Server, in this post, I am using bcp
with xp_cmdshell
.
We will first create a simple select statement to test whether we can export our data, then we will use a stored procedure to handle complex queries. Finally we will try to add variables to our script so that we can make this export script to be run in SQL Server Agent as a scheduled task.
Test the export with a simple select statement
|
However, you will receive an error of: [SQL Server]Invalid object name ‘Table’.
So, in order to run this simple query, we actually need to tell SQL Server the full name of our table schema, which should be:
|
Complex Query, use stored procedure
For a complex query, we should store our query in a Stored Procedure, for example if we have a stored procedure name ExportDataSeries
with two DateTime
input parameters, we can change our script to:
|
Refactor and apply variables for the query
Now that we have worked out our stored procedure, let’s try to refactor our script by injecting some variables, such that we can use this in SQL Server Agent for repeated task. In this case, let’s assume this is a daily schedule which will export data to a CSV file everyday.
The final script looks like this:
|
For your interest, variable @BcpStatement
looks like this:
|