Call SQLCMD to run SQL script via C#
Usually, we need to call some sql script to update our database in our application(C#), and it is a good way to call SQLCMD to execute the sql scripts. One important reason is that our scripts always contains the GO statement which is is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. Since the SQLCMD and SQL Server Management Studio will do the same thing, the scripts edited by SQL Server Management Studio will be 100% supported by SQLCMD.
Here is a block of code to call SQLCMD:
string tmpFile = Path.GetTempFileName(); string argument = string.Format(@" -S {0} -d {1} -i ""{2}"" -o ""{3}""", ServerName, DatabaseName, fileName, tmpFile); // append user/password if not use integrated security if (!connection.IsIntegratedSecurity) argument += string.Format(" -U {0} -P {1}", User, Password); var process = Process.Start("sqlcmd.exe", argument); process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); while (true) { // wait for the process exits. The WaitForExit() method doesn't work if (process.HasExited) break; Thread.Sleep(500); }
