GENERATING SQL SCRIPTS FOR STORED PROCEDURES, FUNCTIONS, VIEWS & TRIGGERS



Similar documents
BACKING UP A DATABASE

INTRODUCTION: SQL SERVER ACCESS / LOGIN ACCOUNT INFO:

Note: With v3.2, the DocuSign Fetch application was renamed DocuSign Retrieve.

Hands-On Lab. Client Workflow. Lab version: Last updated: 2/23/2011

I A Form és a párbeszédablakok I.1. MessageBox osztály MessageBox.Show(szöveg[,cím[,gombok[,ikon[,defaultbutton]]]]);

CRM Setup Factory Installer V 3.0 Developers Guide

Installation Guide for Microsoft SQL Server 2008 R2 Express. October 2011 (GUIDE 1)

Application Development

Jolly Server Getting Started Guide

ACCESSING IBM iseries (AS/400) DB2 IN SSIS

SPHOL207: Database Snapshots with SharePoint 2013

Integrating InfoPath Forms. Paul Baker

Sitecore Ecommerce Enterprise Edition Installation Guide Installation guide for administrators and developers

How to set up SQL Source Control. The short guide for evaluators

Using SQL Server Management Studio

Video Administration Backup and Restore Procedures

ADOBE READER AND ACROBAT

MS SQL Server Database Management

Getting Started with ODM

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

SQL Server 2005: Server Management Objects (SMO)

Paging, sorting, and searching using EF Code first and MVC 3. Introduction. Installing AdventureWorksLT database. Creating the MVC 3 web application

How to Backup and FTP your SQL database using E2.

Suite. How to Use GrandMaster Suite. Exporting with ODBC

Tutorial: How to Use SQL Server Management Studio from Home

Auditing manual. Archive Manager. Publication Date: November, 2015

Moving a Romexis Database to an Existing SQL Instance

Avatier Identity Management Suite

1. Create SQL Database in Visual Studio

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

Product: DQ Order Manager Release Notes

AssetGen Desktop Professional Download and Installation Instructions

Guidelines for Installing SQL Server and Client (SQL Server Management Studio)

Visual Basic. murach's TRAINING & REFERENCE

MS Enterprise Library 5.0 (Logging Application Block)

A Tutorial on SQL Server CMPT 354 Fall 2007

SQL Server An Overview

InformationNOW SQL 2008 Database Backup and Restoration

Microsoft SQL Server Scheduling

EASRestoreService. Manual

Visual COBOL ASP.NET Shopping Cart Demonstration

ecopy ShareScan 5.0 SQL installs guide

StreamServe Persuasion SP4

CPM release notes

Specialized Programme on Web Application Development using Open Source Tools

CHAPTER 10: WEB SERVICES

TABLE OF CONTENTS. avaya.com

USING FILERELICATIONPRO TO REPLICATE SQL SERVER

How To Create An Easybelle History Database On A Microsoft Powerbook (Windows)

WirelessOffice Administrator LDAP/Active Directory Support

Review of SwisSQL Data Migration Tool

Beginning MYSQL 5.0. With. Visual Studio.NET 2005

UC BERKELEY EXTENSION

USING MYWEBSQL FIGURE 1: FIRST AUTHENTICATION LAYER (ENTER YOUR REGULAR SIMMONS USERNAME AND PASSWORD)

SQL 2012 Installation Guide. Manually installing an SQL Server 2012 instance

ClientAce WPF Project Example

ASPEN Relay Database Version 11.2 Release

GoDaddy (CentriqHosting): Data driven Web Application Deployment

EZManage SQL Pro. Quick guide for installation and implementation

ASP.NET Dynamic Data

Microsoft SQL connection to Sysmac NJ Quick Start Guide

Abstract. For notes detailing the changes in each release, see the MySQL for Excel Release Notes. For legal information, see the Legal Notices.

MyOra 3.5. User Guide. SQL Tool for Oracle. Kris Murthy

Using Microsoft SQL Server A Brief Help Sheet for CMPT 354

Big Data and Analytics by Seema Acharya and Subhashini Chellappan Copyright 2015, WILEY INDIA PVT. LTD. Introduction to Pig

MyOra 4.5. User Guide. SQL Tool for Oracle. Kris Murthy

SourceAnywhere Service Configurator can be launched from Start -> All Programs -> Dynamsoft SourceAnywhere Server.

Installing C++ compiler for CSc212 Data Structures

SQL Injection. Sajjad Pourali CERT of Ferdowsi University of Mashhad

Setting up an MS SQL Server for IGSS

Checking SQL Server or MSDE Version and Service Pack Level

GETTING STARTED WITH SQL SERVER

**Web mail users: Web mail provides you with the ability to access your via a browser using a "Hotmail-like" or "Outlook 2003 like" interface.

Remote Management System

How To Create A Replica In A Database On A Microsoft Powerbook (Ahem) On A Linux Server (A.K.A.A)

Installation of MSSQL Server 2008 Express Edition and Q-Monitor 3.x.x

Database Master User Manual

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio Lab version: Last updated: 12/10/2010.

Synchronizing databases

Visual Studio.NET Database Projects

Installation of MSSQL Server 2005 Express Edition and Q-Monitor 3.x.x

InformationNOW SQL 2005 Database Backup and Restoration

Advantage for Windows Copyright 2012 by The Advantage Software Company, Inc. All rights reserved. Client Portal blue Installation Guide v1.

Windows Server Update Services 3.0 SP2 Step By Step Guide

Crystal Reports Setup

Copyright Texthelp Limited All rights reserved. No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval

Two new DB2 Web Query options expand Microsoft integration As printed in the September 2009 edition of the IBM Systems Magazine

Basic SQL Server operations

Microsoft SQL Server Features that can be used with the IBM i

TSM Studio Server User Guide

SQL DATABASE PROGRAMMING (PL/SQL AND T-SQL)

Chapter 4 Accessing Data

HansaWorld SQL Training Material

Create Reports Utilizing SQL Server Reporting Services and PI OLEDB. Tutorial

Tool Tip. SyAM Management Utilities and Non-Admin Domain Users

Migrating to Azure SQL Database

Network Event Viewer now supports real-time monitoring enabling system administrators to be notified immediately when critical events are logged.

How To Set Up Safetica Insight 9 (Safetica) For A Safetrica Management Service (Sms) For An Ipad Or Ipad (Smb) (Sbc) (For A Safetaica) (

Using IRDB in a Dot Net Project

Transcription:

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 -