Monday, 1 February 2016

Execute a script in c#

you have to take reference of  these


url of that file will be
C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies
these will come after install the sql server 
private bool ExecuteScript(SqlConnection conn)
        {
            try
            {
                string strSqlFilePath = Properties.Settings.Default.sqlScriptPath;
                string strFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + strSqlFilePath;
                string script = File.ReadAllText(@strFilePath);
                ServerConnection servCon = new ServerConnection(conn);
                servCon.StatementTimeout = 240;
                Server server = new Server(servCon);
                conn.Open();
                server.ConnectionContext.ExecuteNonQuery(script);
            }
            catch (System.Exception ex)
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                MessageBox.Show("Please Check Server and database name. Incorrect Server and database name.", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            return true;
        }

No comments:

Post a Comment