SQL Server 2008 R2 Express, .Net Framework 4.0, Visual Studio 2010
I'm trying to execute a SQL script from a command prompt application. I found a sample
code and trying to implement the same. But the following using statements are not recognized.
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
Am I missing any assembly reference ?
You likely are, you need the assemblies that are included with the SDK that comes with SQL server. Be sure you installed the SDK when you installed SQL server.
(screenshot taken from a random google image search, the highlighted item is what you need)
By default they are located at a path similar to C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies
The version number may be different for the version of SQL server you have installed.
Following c# code uses SMO(SQL Server Management Object) to read any
sql query from a .sql file and execute on SQL server.
#region Using Directives
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Xml.Linq;
using System;
#endregion
public sealed class DatabaseHandler
{
#region Properties
/// <summary>
/// Returns the Database Connection String
/// </summary>
public string ConnectionString
{
get
{
return ConfigurationManager.AppSettings["DbConnectionString"];
}
}
#endregion
#region Public Methods
/// <summary>
/// Reads the script conent from .sql file and execute on SQl Server
/// </summary>
/// <param name="scriptFilePath">.sql Script file path</param>
/// <returns>Operation status <c>true: Success</c><c>false: Failed</c></returns>
public bool ExecuteScript(string scriptFilePath)
{
try
{
bool isCreated = false;
if (!string.IsNullOrWhiteSpace(scriptFilePath))
{
FileInfo fileInfo = new FileInfo(scriptFilePath);
if (null != fileInfo)
{
//Holds the sql script as string
string scriptText = string.Empty;
using (StreamReader reader = fileInfo.OpenText())
{
if (null != reader)
{
scriptText = reader.ReadToEnd();
}
}
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
Server sqlServer = new Server(new ServerConnection(connection));
if (null != sqlServer && null != sqlServer.ConnectionContext)
{
sqlServer.ConnectionContext.ExecuteNonQuery(scriptText);
}
}
}
}
isCreated = true;
return isCreated;
}
catch (FileNotFoundException)
{
throw new FileNotFoundException("Unable to find" + scriptFilePath);
}
catch (Exception)
{
throw;
}
}
#endregion
}
Now that it's 2017, there is an easier way.
Add this NuGet package:
https://www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects