Published on

February 28, 2009

Scripting SQL Server Objects using SQL-DMO COM Object

Introduction:

As a SQL Server developer, there are often times when you need to script out the objects from a SQL Server database to text files. This can be useful for various reasons, such as creating a clean database build process with the most recent changes or maintaining these script files in a source control repository. While there are different methods available to script out the objects, this article will focus on using the SQL-DMO COM object with VB Script to automate the process.

Background:

The SQL-DMO (Distributed Management Objects) COM interface provides a way to programmatically manage SQL Server. It offers an interface to connect to a SQL Server database and script out its objects. This article will demonstrate how to use the SQL-DMO.SQLServer2 COM interface to script out SQL Server objects.

Using the Code:

The code provided in this article connects to a SQL Server database using either Windows or SQL Server authentication. Once connected, it iterates through the collection of objects in the database and scripts each one of them. The script can be run using the command line syntax:

cscript 0g_sqlextract.vbs [server] [database] [output folder] [username] [password]

The script supports different scripting options, such as including headers, generating Transact-SQL creating the referenced component, including object permissions, and more. These options can be customized based on your requirements.

The code is divided into three main areas:

  1. Constant declarations: These are needed to provide different scripting options.
  2. Main subroutine: Handles parameter validation and drives the calls to script the objects.
  3. ScriptObjects subroutine: Iterates through the elements of the collection and scripts each object.

Conclusion:

This article has provided an approach to script out SQL Server objects using the SQL-DMO COM object. By automating this process, you can have a clean database build process with the most recent changes and maintain these script files in a source control repository. The code provided can be customized based on your specific requirements and can be used with any language that supports COM. It is important to note that this article only covers a small subset of the functionality available using SQL-DMO. If you are looking for an automated build and source control process, this article can provide you with some direction.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.