This depends on what sort of files they are. If, for example, they only contain actual T-SQL commands (and aren't batch files that you'd run in, say, SSMS, which would contain a batch separator like GO
), then you just need to create a connection, a command, then read the contents of the file and use that to populate the CommandText
property of the command.
For example:
void ExecuteFile(string connectionString, string fileName)
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
string data = System.IO.File.ReadAllText(fileName);
conn.Open();
using(SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = data;
cmd.ExecuteNonQuery();
}
}
}
If it's a batch file, you'll need to split the file into individual batches and process those individually. The simplest method is just to use string.Split
, but bear in mind that it won't respect SQL parsing rules when it splits (for example, if GO
appears within a SQL statement, it's going to split the command up into two batches, which will obviously fail).
More generally, you can see what you'd need to do here by modifying the code in this way:
string[] batches = SplitBatches(System.IO.File.ReadAllText(fileName));
conn.Open();
using(SqlCommand cmd = conn.CreateCommand())
{
foreach(string batch in batches)
{
cmd.CommandText = batch;
cmd.ExecuteNonQuery();
}
}
The implementation of a function called SplitBatches
is up to you.