This tip isn't really anything much, just a tidbit to stuff away in the file folder of useful snippets. Therefore I am putting this in the Scrapbook section.
Running a Transact-SQL Query in a Quick-And-Dirty Fashion
Say I have a .sql file and I want to run it very quickly against a certain database on my computer. I happen to know I can connect to a database using plain-old-fashioned Windows Authentication and integrated security, so we aren't doing anything fancy.
Tutorial: Northwind Database
This small tutorial assumes you've downloaded and installed the Northwind database on your instance of SQL Server Express. If not, see my article at HowTo: Install the Northwind and Pubs Sample Databases
] if you're using SQL Server 2005 Express, or HowTo: Install the Northwind and Pubs Sample Databases in SQL Server 2008 Express
] if you're using SQL Server 2008 Express.
Let's create a .sql query file for use against the Northwind database, which I will say is on the
instance on my computer, called
as its computer name.
The following code is in the MyQuery.sql file:
SELECT TOP 10 * FROM Customers
I typed the above into Notepad and then saved it as myQuery.sql
on the Desktop. Now let's whip it off. Click the Start button, and then click Command Prompt.
Next, at the C:\>
C:\Users\bchart\Desktop\> sqlcmd -S COMPUTER\SQLEXPRESS -d Northwind -i myQuery.sql
That's all you do if you want to exec a quickie query from a .sql
script file against a specific server instance and database. Type:
C:\Users\bchart\Desktop\> sqlcmd -?
For more juicy command-line goodness
Now Let's Put this To Work
This is a great tip, because what if you have a command-line console application you've written in C# to do, e.g., automated database reporting, and you have it living as, e.g., a Scheduled Task. Now what if you have some .sql
Transact-SQL script you need that process to run and it's some ungodly long stored-procedure creation script or whatever.
Well, with the tip above, just make a C# call to run the command line above from your code, as in:
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "sqlcmd.exe";
process.StartInfo.Arguments = "-S COMPUTER\\SQLEXPRESS -d Northwind -i myQuery.sql";
process.StartInfo.WorkingDirectory = @"C:\Users\bchart\Desktop";
This C# code does identically the same thing as when I ran the command line above by hand from the Command Prompt. Clickety to this nice article
] to learn more about spawning child processes from code!