You are here
Home > Programming > Exporting SQL Query Results to a CSV file using SQLCMD and C#

Exporting SQL Query Results to a CSV file using SQLCMD and C#

Exception Thrown

Today a colleague asked me how to export SQL Query Results to a CSV file. This got me thinking that it would be a nice exercise to do this from a C# application.

So to start off, I downloaded the correct AdventureWorks database for my version of SQL from the following CodePlex page.

I attached the database and wrote a short piece of code to execute SQLCMD from C#.

SQL Results CSV File

The SQL command I wanted to execute is as follows:

SELECT BusinessEntityID,AccountNumber,Name,PreferredVendorStatus,ActiveFlag,ModifiedDate FROM AdventureWorks2008R2.Purchasing.Vendor WHERE CreditRating >= 3

The command that needs to execute from C# is thus as follows:


SQLCMD -S DIRK-DELLSQLSERVER -d AdventureWorks2008R2 -U sa -P mypassword -Q "SELECT [BusinessEntityID],[AccountNumber],[Name],[PreferredVendorStatus],[ActiveFlag],[ModifiedDate] FROM AdventureWorks2008R2.Purchasing.Vendor WHERE [CreditRating] >= 3 " -s "," -o "c:tempVendorResults.csv"

The format is as follows:

SQLCMD -S YourSQLServer -d YourDatabase -U YourUserName -P YourPassword -Q “Your Query” -s “,” -o “C:Yourfilename.csv”

Running this from  the command prompt will create a CSV file at the path you specified. So putting this all together, fire up your Visual Studio and create the following method.

private void RunProcess()
{
string FileName = "SQLCMD";
string Arguments = @"-S DIRK-DELLSQLSERVER -d AdventureWorks2008R2 -U sa -P mypassword -Q ""SELECT [BusinessEntityID],[AccountNumber],[Name],[PreferredVendorStatus],[ActiveFlag],[ModifiedDate] FROM AdventureWorks2008R2.Purchasing.Vendor WHERE [CreditRating] >= 3 "" -s "","" -o ""c:tempVendorResults.csv""";

ProcessStartInfo proc = new ProcessStartInfo(FileName, Arguments);
proc.UseShellExecute = false;
proc.CreateNoWindow = true;
proc.WindowStyle = ProcessWindowStyle.Hidden;

Process p = new Process();
p.StartInfo = proc;

p.Start();
p.WaitForExit();
}

Running your application creates the CSV file in the path specified. Opening the file, you can see the results.

CSV File Output from C# SQLCMD

The uses for this are endless, and can extend the functionality of your applications tremendously with a few lines of simple C# code.

Reference: Pinal Dave

Dirk Strauss
Dirk is a Software Developer from South Africa. He loves all things Technology and is slightly addicted to Jimi Hendrix. Apart from writing code, he also enjoys authoring books and articles. "I love sharing knowledge and connecting with people from around the world. It's the diversity that makes life so beautiful." Dirk feels very strongly that pizza is simply not complete without Tabasco, that you can never have too much garlic, and that cooking the perfect steak is an art he has almost mastered.
https://dirkstrauss.com

Similar Articles

Top