GENERATING SQL SCRIPTS FOR STORED PROCEDURES, FUNCTIONS, VIEWS & TRIGGERS April 2011 Level: By : Feri Djuandi Beginner Intermediate Expert Platform : MS SQL Server 2008, Visual C# 2010 Pre requisites: Suggested to read the first part of this document series titled Connecting the SQL Server as the introduction and basic. In this article we are going to learn how to generate the SQL scripts for stored procedures, functions, views and triggers using SQL Server Management Objects (SMO). Following are the tools used for the program demo: MS SQL Server 2008 Evaluation Edition MS Visual C# 2010 Express Please open the sample program SmoPractice06.zip attached to this document. Go ahead extracting the ZIP file into your local computer and open the project file. Try to run the program, and you will find a screen like this. - 1 -
As you change the Database from the combo box, the object list under it will change accordingly. As you are aware, objects in SQL Server 2008 and 2005 (e.g. tables, stored procedures, views etc) are identified by a schema name followed by the object name itself. It is important to understand because the same object name under a specified schema may appear in another schema. It is common and allowed in SQL Server 2008 although ultimately the combination of schema and object name should be unique in a SQL Server instance. This demo program allows you to see all stored procedures, functions, views and triggers in the database; or filter only for a specified object displayed. Those four types are programmable objects that contain SQL script that we are interested in. Be noted, that the list only contains user objects and we exclude the system objects from the list, that s why we may see a shorter list compared to what is seen in the MS SQL Server Management Studio. To generate a SQL script, simply choose an object then press the Generate Script button. A SQL file will be created immediately comprising lines of T-SQL program of the selected object. Now stop the program and look into the source code, let us see how the program works. The first line of the Form class contains a constant declaration of the SQL Server instance. This value should be changed according to your SQL Server installation because (local)\sql2k8 is the instance name that specified in my installation. Next is the declaration of the ServerConnection object to specify the connection parameter to the SQL Server; and finally the Server object as the central of the SMO operation. private const string INSTANCE_NAME = "(local)\\sql2k8"; private Microsoft.SqlServer.Management.Common.ServerConnection conn = new ServerConnection(INSTANCE_NAME); private Microsoft.SqlServer.Management.Smo.Server server; private void Form1_Load(object sender, EventArgs e) try //Login using Windows Authentication conn.loginsecure = true; conn.connect(); server = new Server(conn); //Enumerate the database list foreach (Database db in server.databases) //add the Data to the combobox. cbodatabase.items.add(db.name); lvobject.columns.add("name", 300); lvobject.columns.add("type", 150); lvobject.columns.add("parent", 150); - 2 -
As the program is executed, it immediately tries to connect the SQL Server using Windows authentication. This is done by setting the LoginSecure to True, followed by calling the Connect method. Another alternative to connect is through the SQL Server authentication. If you wish to have more explanations on various methods to connect the SQL Server, please read the first article as suggested earlier. The next lines are used to retrieve the database list from the SQL Server instance and put it in a combo box. Finally the last lines prepare the header of the list view control for the table list. The table list is refreshed each time the database selection in the combo box is changed, the All check box is cleared or marked, or the object type radio buttons are changed. The piece of code that refreshes the object list is show in the following script. private void RefreshObjectList() //enumerate user stored procedures if (splist) foreach (Microsoft.SqlServer.Management.Smo.StoredProcedure sp in database.storedprocedures) if (!sp.issystemobject) //show only user objects ListViewItem item = this.lvobject.items.add(sp.schema + "." + sp.name); item.subitems.add("stored Procedure"); //enumerate user functions if (funclist) foreach (Microsoft.SqlServer.Management.Smo.UserDefinedFunction fn in database.userdefinedfunctions) if (!fn.issystemobject) //show only user objects ListViewItem item = this.lvobject.items.add(fn.schema + "." + fn.name); item.subitems.add("function"); //enumerate user views if (viewlist) foreach (Microsoft.SqlServer.Management.Smo.View vw in database.views) if (!vw.issystemobject) //show only user objects - 3 -
ListViewItem item = this.lvobject.items.add(vw.schema + "." + vw.name); item.subitems.add("view"); //enumerate user triggers if (triggerlist) //enumerate the tables first, then the triggers afterward foreach (Microsoft.SqlServer.Management.Smo.Table tbl in database.tables) if (!tbl.issystemobject) //only user objects foreach (Microsoft.SqlServer.Management.Smo.Trigger tr in tbl.triggers) ListViewItem item = this.lvobject.items.add(tbl.schema + "." + tr.name); item.subitems.add("trigger"); item.subitems.add(tbl.name); The program responsible to generate the SQL script file is displayed as follow. Firstly the program opens a dialog window for you to enter the file name for the SQL script file to be generated. The subsequent lines determine which object that selected from the list, then identifying the object type, schema name and the object name. The SQL script is produced by executing the Script method of the corresponding object where its output is stored in a StringCollection object. Later each string (that represents a line of SQL command) should be extracted from the collection and appended line by line to construct a complete T-SQL program in a text format. private void btngeneratescript_click(object sender, EventArgs e) if (savefiledialog1.showdialog() == DialogResult.OK) string filename = savefiledialog1.filename; string dbname = cbodatabase.items[cbodatabase.selectedindex].tostring(); Microsoft.SqlServer.Management.Smo.Database database = server.databases[dbname]; ListViewItem item = this.lvobject.selecteditems[0]; string itemname = item.subitems[0].text; - 4 -
string objtype = item.subitems[1].text; int i = itemname.indexof(".", 0); string objname = itemname.substring(i + 1, itemname.length - i - 1); string objschema = itemname.substring(0, i); StringCollection sc=null; string s1 = ""; //generate the SQL script switch(objtype) case "Stored Procedure": Microsoft.SqlServer.Management.Smo.StoredProcedure sp = database.storedprocedures[objname, objschema]; sc = sp.script(); case "Function": Microsoft.SqlServer.Management.Smo.UserDefinedFunction fn = database.userdefinedfunctions[objname, objschema]; sc = fn.script(); case "View": Microsoft.SqlServer.Management.Smo.View vw = database.views[objname, objschema]; sc = vw.script(); default: //Trigger string objparent = item.subitems[2].text; Microsoft.SqlServer.Management.Smo.Table tbl = database.tables[objparent, objschema]; Microsoft.SqlServer.Management.Smo.Trigger tr = tbl.triggers[objname]; sc = tr.script(); foreach (string s in sc) s1 += s + Environment.NewLine; //write the script to the SQL file try TextWriter tw = new StreamWriter(fileName); tw.writeline(s1); tw.close(); MessageBox.Show("File " + filename + " is successfully writen.", "SQL Script", MessageBoxButtons.OK, MessageBoxIcon.Information); catch (Exception ex) MessageBox.Show(ex.Message); - 5 -
//Your error handling here Finally the file is written through the TextWriter object by passing the T-SQL text constructed earlier as the function parameter. Please also be aware of the I/O exception that may occur when writing a file. Pretty easy, isn t it? That s all you need to know how to enumerate tables and generate the table scripts in SQL Server using SMO. There are more another interesting and easy-to-learn articles in this SMO series. Please continue reading and enjoy! - 6 -