My goal is trying to install stored procedures that are in .sql files. After doing some research, everyone recommended that my program reads in the .sql file into a string and create a command object from the string.
using System.Data.SqlClient;
public partial class ExecuteScript
{
static void Main(string[] args)
{
string sqlConnectionString = [connection string];
string script = File.ReadAllText([.sql file path]);
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
Here are some references:
- How to execute an .SQL script file using c#
- https://social.msdn.microsoft.com/Forums/en-US/43e8bc3a-1132-453b-b950-09427e970f31/run-a-sql-script-file-in-c?forum=adodotnetdataproviders
It is interesting that sqlcmd.exe takes in .sql file but SqlClient in .NET does not. Does anyone know why or how to? The reason I do not want to read in .sql file as a string is that all my stored procedures have comments at the top and reading them into a string makes the entire procedure into a sql comment. I understand I can fix this various ways but I was hoping to see if there is a easier way. I ended up doing the following but please enlighten me!
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = "-E -d [database] -S [server\\instance] -i " + storedProcFullPath;
startInfo.FileName = "sqlcmd.exe";
Process.Start(startInfo);
Thanks!