Introduction
Sometimes we need to run *.sql script from our application to install the database. SqlCommand is not right for running the installation script because the installation script consists of DDL and GO commands. Here we use smo library for executing the *.sql script.
For doing the above operation, we need to add the following references
- Microsoft.SqlServer.ConnectionInfo
- Microsoft.SqlServer.Smo
If you are unable to find the above references
Took me a few minutes to find at first. If you can't find them in the .NET tab, you might not have them installed. The paths on my computer to these files are:
- c:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
- c:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
Then we need to add the following namespaces
using System.IO;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
Then we need to use the following code for executing the *.sql script
string sqlConnectionString = txtConstring.Text; //connection string
FileInfo file = new FileInfo(path + "Procedure_fn.sql"); //*.sql file path
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
Seema PahwaPosted Jan 6, 2016, 2:14 PM
I am getting error This SQL version version 10.0 is not supported
Upendra Pratap ShahiPosted May 29, 2015, 1:13 AM
string sqlConnectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ToString(); FileInfo file = new FileInfo("C:\\script.sql"); string script = file.OpenText().ReadToEnd(); SqlConnection conn = new SqlConnection(sqlConnectionString); SqlCommand command = new SqlCommand(script, conn); command.Connection.Open(); command.ExecuteNonQuery(); command.Connection.Close();
Upendra Pratap ShahiPosted May 29, 2015, 1:13 AM
nice...
umer aliPosted Feb 2, 2015, 2:07 AM
string sqlconstring = "Data Source=(local);Initial Catalog=dbname;Integrated Security=True";
umer aliPosted Feb 2, 2015, 2:06 AM
u have to create connection string eg
abdus salamPosted Apr 2, 2014, 2:00 AM
I am getting this error "Failed to connect to server Data Source=(local);Initial Catalog=DatabaseName;User ID=sa; Password=123123;."