Execute sql script on SQL server using C#

你。 提交于 2019-11-29 18:06:20

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!