Introduction
This article is about an SQL Script Reader or Executer that executes the scripts which are already generated and you want to execute them. Just change the path where your scripts reside.
Background
If you have some generated scripts and you want to execute them, then modify those scripts.
Using the Code
Execute the scripts which are already generated and you want to execute them. Just change the path where your scripts reside. If you have multiple scripts and want to execute them all at the same time, then use array which contains the path of your directory and name of the scripts:
using System;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Nmo;
using Microsoft.SqlServer.Management.Smo.Agent;
namespace SQL_ScriptReader
{
public class scriptReader
{
public scriptReader()
{
}
public void ReadScript(string ConnectionString)
{
string sqlConnectionString = ConnectionString;
FileInfo file = new FileInfo(@"d:\script.txt");
string script = file.OpenText().ReadToEnd();
Server server = new Server();
server.ConnectionContext.ConnectionString = sqlConnectionString;
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
I have not used try catch
block. You can use it for your code efficiency.
History
- 10th September, 2007: Initial post