Click here to Skip to main content
Click here to Skip to main content

How to Script Out SQL Server Objects

By , 10 Feb 2009
 

Introduction

I usually come across the need to script out the objects from an SQL Server database to text files. I like to create one script per object, with different file extensions to identify the object type. There are many ways this can be done. One can connect to the SQL Server and script out the objects using Enterprise Manager. One can use Visual Studio and create a database project. This too allows you to script out the object. However, these methods are not effective if you want to automate this process. One should think about a continuous integration process which can allow one to have a clean database build process with the most recent changes. Another benefit is the ability to maintain these script files in a source control repository.

Purpose/Scope

The main goal of this article is to show an approach of how to script out the SQL Server objects using the SQL-DMO COM object. There are other approaches, but the focus on this article is using this COM object with VBScript. Any other language which supports COM can be used to achieve the same. This script has been tested using SQL 2000/2005, MSDE/Express.

Background

This script uses the SQLDMO.SQLServer2 COM interface. DMO stands for Distributed Management Objects. It provides an interface to programmatically manage SQL Server. The reader is encouraged to read further on this topic.

Using the Code

This script connects to a SQL Server database using Windows or SQL Server authentication. Once it is connected, it iterates through the collection of objects in the database and scripts each one of them.

The command line syntax to run the script is as follows:

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

[server]

server location/IP address/instance name

[database]

database name/initial catalog

[output folder]

a folder (must exist) where to write the files to

[username]

user (optional - SQL authentication)

[password]

password (optional)

The usage for a SQL Express instance with Windows authentication is:

cscript 0g_sqlextract.vbs localhost\my-sql-instance mydatabase c:\sqloutput

The usage for a SQL 2000 server with SQL Server authentication is:

cscript 0g_sqlextract.vbs localhost mydatabase c:\sqloutput sa mypassword

The code is divided into three main areas. There are the constant declarations which are needed to provide the different scripting options. For example, if one wants the script to first drop the object before creating it. The entry point, Main, handles the parameter validation and drives the calls to script the objects and the ScriptObjects subroutine which iterates through the elements of the collection.

The constant definitions are needed when a call to the Script method is made. There are other options, but these are the ones used in this article.

'List all Microsoft® SQL Server™ components that 
'depend on the referenced SQL Server component.
const SQLDMODep_Children = 262144
'Apply descending order to returned list.
const SQLDMODep_OrderDescending = 131072
'SQLDMOScript_DRI_Checks, SQLDMOScript_DRI_Defaults, 
'SQLDMOScript_DRI_ForeignKeys, SQLDMOScript_DRI_PrimaryKey, and 
'SQLDMOScript_DRI_UniqueKeys
const SQLDMOScript_DRI_AllConstraints=520093696 
const SQLDMOScript_ToFileOnly = 64              'output file
const SQLDMOScript_OwnerQualify =  262144       'object owner
'Generate Transact-SQL creating the referenced component.
const SQLDMOScript_PrimaryObject = 4
'Include Transact-SQL privilege defining statements 
'when scripting database objects.
const SQLDMOScript_ObjectPermissions = 2
const SQLDMOScript_IncludeIfNotExists =4096     'if exists
const SQLDMOScript_Indexes = 73736              'indexes
const SQLDMOScript2_NoCollation = 8388608       'no collation
const SQLDMOScript_Triggers = 16                'triggers
'Generate Transact-SQL to remove the referenced component. 
'Script tests for existence prior attempt to remove component.
const SQLDMOScript_Drops = 1
const SQLDMOScript_DRI_NonClustered = 4194304
const SQLDMOScript_DRI_Clustered = 8388608
const SQLDMOScript_DRI_Checks = 16777216
const SQLDMOScript_DRI_Defaults = 33554432
const SQLDMOScript_DRI_UniqueKeys = 67108864
const SQLDMOScript_DRI_ForeignKeys = 134217728
const SQLDMOScript_DRI_PrimaryKey = 268435456
const SQLDMOScript_DRI_AllKeys = 469762048
const SQLDMOScript_DRIWithNoCheck = 536870912
const SQLDMOScript_DRI_All = 532676608
const SQLDMOScript_NoIdentity = 1073741824

'folder definitions
const PROC_FOLDER = "\stored procedures"
const VIW_FOLDER ="\views"
const UDF_FOLDER = "\functions"
const TAB_FOLDER ="\tables"

The Main subroutine reads the arguments. The arguments are referenced by the objArgs variable which holds an array of values. The first three parameters are required. The last two parameters are optional. A reference to the COM interface is created:

Set oSql = WScript.CreateObject("SQLDMO.SQLServer2")

If only three arguments are passed, the script sets the LoginSecure property to True, which indicates that Windows Authentication is used to connect to the database. Otherwise, SQL Authentication is used. Once the connection is successful, calls to ScriptObjects are made using the following collections:

  • oSql.Databases(database).Tables
  • oSql.Databases(database).Views
  • oSql.Databases(database).StoredProcedures
  • oSql.Databases(database).UserDefinedFunctions
sub Main
           
   'get the parameter list   

   dim objArgs: Set objArgs = WScript.Arguments

   if objArgs.Count > 2 then
    connString = objArgs(0)   'connection   

    database = objArgs(1)     'database

    folder = objArgs(2)       'output folder      


    dim user
    dim pw

    Set oSql = WScript.CreateObject("SQLDMO.SQLServer2")      
        
    if objArgs.Count > 4 then
        user = objArgs(3) 
        pw = objArgs(4) 
        StdOut.Echo "SQL Authentication - Connection to database"

        oSql.LoginSecure = False            'SQL authentication 

        oSql.Connect connString ,user,pw   
    else
        StdOut.Echo "windows Authentication - Connection to database"
        oSql.LoginSecure = True   'windows authentication 

        oSql.Connect connString   
    end if
                                                
    call ScriptObjects(oSQL.Databases(database).Tables,"TAB",_
                       "Reading tables: ")
    call ScriptObjects(oSQL.Databases(database).Views,"VIW",_
                       "Reading views: ")      
    call ScriptObjects(oSQL.Databases(database).StoredProcedures,_
                       "PRC","Reading procedures: ")      
    call ScriptObjects(oSQL.Databases(database).UserDefinedFunctions,_
                       "UDF","Reading functions: ")      
                    
    oSql.Disconnect     
      
   else
    StdOut.Echo "Usage: sqlextract.vbs [server or sql " & _ 
                "instance name] [database] [output folder]"   
   end if

    set oSql = nothing  
    
    if err.Description <> "" then        
        StdOut.Echo err.Description
    end if

end sub

The ScriptObjects subroutine iterates through the elements in the list. It checks to make sure the object is not a SystemObject. This is because one only needs to script out user objects. The options are a combination of constant values which are passed as an argument to the Script method. This is what allows us to create additional information in the script. This information can be constraint definitions, triggers, options to look if object exists and to drop it before creating it. There are also two additional arguments to this subroutine, ext and msg. The ext argument is used as the file extension. The msg argument is used to display the status of what is being generated. The format of the files generated is OWNER.OBJECTNAME.EXTENSION, so for the MyProc stored procedure which belongs to dbo, the script generated would be: dbo.MyProc.PRC.

sub ScriptObjects(list,ext,msg)
 
    Dim object
    StdOut.Echo ""
    StdOut.Echo msg 
    
    'set the scripting options

    dim options
    options = SQLDMOScript_Indexes _
            OR SQLDMOScript_Drops _
            OR SQLDMOScript_IncludeIfNotExists _
            OR SQLDMOScript_OwnerQualify _
            OR SQLDMOScript_PrimaryObject _
            Or SQLDMODep_Children _
            Or SQLDMOScript_DRI_AllConstraints _
            Or SQLDMODep_OrderDescending _
            Or SQLDMOScript_ObjectPermissions _
            Or SQLDMOScript_ToFileOnly _
            OR SQLDMOScript2_NoCollation _
            OR SQLDMOScript_Triggers _
        OR SQLDMOScript_DRI_All
    
    For Each object In list
    
        If Not object.SystemObject Then
            StdOut.Echo object.Name
            object.Script options, GetFolderName(ext) + "\" + _
                          object.Owner + "." + object.Name + "." + ext
        End If
    
    Next
    
end sub

There are two helper functions to help us create a folder for each object type. The GetFolderName function maps the file extension to a predefined folder name (i.e. TAB = Tables). A call to the CreateFolder subroutine is made to create the folder if it does not already exist. The purpose here is to group the object types in separate folders. This is similar to the way the objects are presented using SQL Server tools.

function GetFolderName(ext)

   dim tmpFolder
   tmpFolder = ""

   select case ext
          case "TAB" tmpFolder = TAB_FOLDER 
    case "VIW" tmpFolder = VIW_FOLDER 
    case "PRC" tmpFolder = PROC_FOLDER 
    case "UDF" tmpFolder = UDF_FOLDER 
    end select

    CreateFolder folder + tmpFolder
    GetFolderName = folder  + tmpFolder

end function

sub CreateFolder(path) 
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    if not fso.FolderExists(path) then
        fso.CreateFolder(path)
    end if

    set fso=nothing

end sub

Points of Interest

This article only covers a small subset of the functionality available using SQL-DMO. If the goal is to have an automated build and source control process, this article can provide you with some direction. I hope some of you can find this useful.

History

  • 0g10112006 - Initial version
  • 0g05102008 - Script table keys and create folders for each object type
  • 0g02092009 - Source code updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

ozkar garcia
Software Developer (Senior) OG-BITechnologies
United States United States
Member

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberOrlando Selenu15 Mar '12 - 23:41 
Thank you very much ozkar!
GeneralRe: My vote of 5memberozkar garcia18 Sep '12 - 4:49 
I am glad to see that it helps
Questionerror when trying to run the scriptmemberonmni20 Aug '11 - 21:25 
could someone tell me what I am doing wrong?
 

 

C:\Temp\0g_SqlExtract_src\0g_sqlextract.vbs(65, 7) WScript.CreateObject: Could n
ot locate automation class named "SQLDMO.SQLServer2".
AnswerRe: error when trying to run the scriptmemberLonyem23 Sep '11 - 7:58 
I'm assuming you're running SQL Server 2008, in which case you need to download and install Microsoft SQL Server 2005 Backward Compatibility Components from http://www.microsoft.com/download/en/details.aspx?id=16177[^]
GeneralMy vote of 5memberprmioto23 Feb '11 - 3:42 
Simple and effective script.
QuestionHow would you script Triggers?memberwooddsw18 Nov '09 - 2:25 
SQLDMO doesn't appear to expose triggers(I don't see anything for triggers in Intellisense). How would this script be enhanced to include triggers?
AnswerRe: How would you script Triggers?memberozkar garcia18 Nov '09 - 4:03 
hello,
 
Take a look at the script (line 187). It uses the SQLDMOScript_Triggers property. This means that when the call to object.script (line 196) is made, the trigger will also be generated inside the TAB file for that table. I often used this option, and I am able to get the triggers that way.
 
If you need to, the table object exposes a triggers collection which allows you to select each trigger object.
 
I hope this helps
GeneralRe: How would you script Triggers?memberwooddsw18 Nov '09 - 4:28 
I see that now. Is it possible to tweak it to only give the triggers and not the entire table create? Maybe even just script only the tables that have the triggers.
 
If I have to I can manually pull the triggers out but I'd prefer to have the entire process automated.
 
Otherwise it's working great for me.
QuestionHave you found a solution to avoid the varchar(-1) generatedmembersingueur19 Aug '09 - 11:00 
instead of varchar(MAX) ?
 
if yes please post the solution
 
Patrick
 
BTW very Nice article.! thanks
QuestionRe: Have you found a solution to avoid the varchar(-1) generatedmemberuuthanh30 Sep '09 - 5:50 
I ran into this issue as well. How difficult to convert this script to use SMO? Can we overcome the varchar(-1) in SMO?
AnswerRe: Have you found a solution to avoid the varchar(-1) generatedmemberozkar garcia30 Sep '09 - 7:54 
There is a small hack to overcome the max to -1 problem.
 
Follow these steps:
 
1) remove the SQLDMOScript_ToFileOnly option from the ScriptObjects subroutine. This allows us to script the object into a variable.
 
2) From the variable , replace varchar (-1) with varchar (max)
 
3) Add a function to write the script to a file.
 
I will update the script with this modification.
 
I will try to work on a version using SMO
 
thanks Cool | :cool:
GeneralRe: Have you found a solution to avoid the varchar(-1) generatedmemberuuthanh30 Sep '09 - 17:09 
thank you very much, ozkar garcia.
can you also replace nvarchar(0) with nvarchar(max) as well?
I found your script very useful and i extended a bit, like:
1. Allow user to specify what type of object to script, e.g. table/view/proc/func
2. Read-in the list of objects to script, e.g. a list of table names
3. etc...
 
I'm sure these are piece of cake to you Smile | :) . Let me know if you're interested, i can share with you.
 
Thanks again.
Answergreat tool ...memberCoosile216 Jul '09 - 12:28 
Hi Ozkar,
 
very good job. That is something you don't want to miss once you saw it. I did some minor improvements.
I very often just add my content to existing DBs. I use a naming scheme that identifies all my USPs, tables and views. And I only want to dump those objects afterwards.
So I added a filter argument. If empty ("") the script dumps everything, if a literal is given it only dumps objects with that string inside the name.
 
It also creates a new folder everytime you run it. It creates a folder for the current date and a subfolder with the current time. So you get a kind of versioning.
 
Thanks again.
 
' Author: ogarcia (og-bit.com)  ; improved by coosile (2009-07-15)
' Date :   10/11/2006
' Usage: cscript dump-sql-objects.vbs [server or sql instance name] [database] [output folder] [pattern]
'
'

Option Explicit
 
Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
dim connString
dim database
dim folder
dim oSql: 
dim pattern
 
const SQLDMODep_Children = 262144               'List all Microsoft® SQL Server™ components that depend on the referenced SQL Server component.
const SQLDMODep_IncludeHeader = 131072        'add a datetime header
const SQLDMOScript_DRI_AllConstraints = 520093696 'SQLDMOScript_DRI_Checks, SQLDMOScript_DRI_Defaults, SQLDMOScript_DRI_ForeignKeys, SQLDMOScript_DRI_PrimaryKey, and SQLDMOScript_DRI_UniqueKeys 
const SQLDMOScript_ToFileOnly = 64              'output file
const SQLDMOScript_OwnerQualify =  262144       'object owner
const SQLDMOScript_PrimaryObject = 4            'Generate Transact-SQL creating the referenced component.
const SQLDMOScript_ObjectPermissions = 2        'Include Transact-SQL privilege defining statements when scripting database objects.
const SQLDMOScript_IncludeIfNotExists =4096     'if exists
const SQLDMOScript_Indexes = 73736              'indexs
const SQLDMOScript2_NoCollation = 8388608       'no collation
const SQLDMOScript_Triggers = 16                'triggers
const SQLDMOScript_Drops = 1                   'Generate Transact-SQL to remove the referenced component. Script tests for existence prior attempt to remove component.

const SQLDMOScript_DRI_NonClustered = 4194304
const SQLDMOScript_DRI_Clustered = 8388608
const SQLDMOScript_DRI_Checks = 16777216
const SQLDMOScript_DRI_Defaults = 33554432
const SQLDMOScript_DRI_UniqueKeys = 67108864
const SQLDMOScript_DRI_ForeignKeys = 134217728
const SQLDMOScript_DRI_PrimaryKey = 268435456
const SQLDMOScript_DRI_AllKeys = 469762048
const SQLDMOScript_DRIWithNoCheck = 536870912
const SQLDMOScript_DRI_All = 532676608
const SQLDMOScript_NoIdentity = 1073741824
 
const PROC_FOLDER = "\stored procedures"
const VIW_FOLDER ="\views"
const UDF_FOLDER = "\functions"
const TAB_FOLDER ="\tables"
Dim dateStr : dateStr = getDateString
Dim timeStr : timeStr = getTimeString
Main
 
sub Main
           
   'get the parameter list   
   dim objArgs: Set objArgs = WScript.Arguments
 
   if objArgs.Count > 2 then
      connString = objArgs(0)   'connection   
      database = objArgs(1)     'database
      folder = objArgs(2)       'output folder      
      pattern = objArgs(3)		'pattern to search for in obj
      
	  logit "Connect to server [" & connString & "] and DB [" & database & "] and store objects in [" & folder & "] and use pattern [" & pattern & "]"
      dim user
      dim pw
      
      Set oSql = WScript.CreateObject("SQLDMO.SQLServer2")      
      
      if objArgs.Count > 4 then
			user = objArgs(3) 
			pw = objArgs(4) 
			StdOut.Echo "SQL Authentication - Connection to database"
			oSql.LoginSecure = False			'sql authentication 
			oSql.Connect connString ,user,pw   
      else
			StdOut.Echo "windows Authentication - Connection to database"
			oSql.LoginSecure = True   'windows authentication 
			oSql.Connect connString   
	  end if
                                                  
      call ScriptObjects(oSql.Databases(database).Tables,"TAB","Reading tables: ")
      call ScriptObjects(oSql.Databases(database).Views,"VIW","Reading views: ")      
      call ScriptObjects(oSql.Databases(database).StoredProcedures,"PRC","Reading procedures: ")      
      call ScriptObjects(oSql.Databases(database).UserDefinedFunctions,"UDF","Reading functions: ")      
                      
      oSql.Disconnect     
      
   else
      StdOut.Echo "Usage: sqlextract.vbs [server or sql instance name] [database] [output folder]"   
   end if
 
    set oSql = nothing  
    
    if err.Description <> "" then        
		StdOut.Echo err.Description
	end if
 
end sub
 

'GetFolderName
'
'resolves the folder name based on the file ext
'
' ext  - extension name
'
function GetFolderName(ext)
	Dim newFolder
   
   dim tmpFolder
   tmpFolder = ""
 
   select case ext
      	case "TAB" tmpFolder = TAB_FOLDER 
	case "VIW" tmpFolder = VIW_FOLDER 
	case "PRC" tmpFolder = PROC_FOLDER 
	case "UDF" tmpFolder = UDF_FOLDER 
    end select
 
	newFolder = folder + "\" + dateStr & "\" & timeStr & "\" & database + tmpFolder
    CreateFolder newFolder
    GetFolderName = newFolder
 
end function
 
'CreateFolder
'
'creates a folder to write files to
'
'path the path to the new folder
sub CreateFolder(path) 
	Dim fso
	Set fso = CreateObject("Scripting.FileSystemObject")
	
	if not fso.FolderExists(fso.GetParentFolderName(path)) Then
		createFolder fso.GetParentFolderName(path)
	End IF
	if not fso.FolderExists(path) then
		fso.CreateFolder(path)
	end if
 
	set fso=nothing
 
end sub
 
'ScriptObjects
'
'scrips all the objects
'
' list   - collection
' ext    - extension name to use
' msg    - message to display
sub ScriptObjects(list,ext,msg)
 
 
    Dim object
    StdOut.Echo ""
    StdOut.Echo msg 
    
    'set the scripting options
    dim options
    options = SQLDMOScript_Indexes _
			OR SQLDMOScript_Drops _
			OR SQLDMOScript_IncludeIfNotExists _
			OR SQLDMOScript_OwnerQualify _
			OR SQLDMOScript_PrimaryObject _
			Or SQLDMODep_Children _
			Or SQLDMOScript_DRI_AllConstraints _
			Or SQLDMODep_IncludeHeader _
			Or SQLDMOScript_ObjectPermissions _
			Or SQLDMOScript_ToFileOnly _
			OR SQLDMOScript2_NoCollation _
			OR SQLDMOScript_Triggers _
			OR SQLDMOScript_DRI_All
    
    For Each object In list
    
		If Not object.SystemObject Then
			If InStr(object.Name, pattern) OR pattern = "" Then
				StdOut.Echo object.Name			                                                
				object.Script options, GetFolderName(ext)   + "\" + object.Owner + "." + object.Name + "." + ext  	                                                          
			End If
		End If
    
    Next
    
end sub
 
'**************************************
'gets current date and time in a sorable 
'format
Function getDateString()
	Dim dtDay
	Dim dtMonth
	Dim dtYear
	Dim dt
	
	dt = Date
	dtDay = formatDT(Day(dt))
	dtMonth = formatDT(Month(dt))
	dtYear = formatDT(Year(dt))
	
	getDateString = dtYear & "-" & dtMonth & "-" & dtDay
End Function
 

'**************************************
'gets current date and time in a sorable 
'format
Function getTimeString()
	Dim dt
	Dim dtH, dtM, dtS
	
	dt = Time
	dtH = formatDT(Hour(dt))
	dtM = formatDT(Minute(dt))
	dtS = formatDT(Second(dt))
 
	getTimeString = dtH & "-" & dtM & "-" & dtS
End Function
 
'**************************************
'handles single character date parts
Function formatDT( dtpart )
	If dtpart < 10 Then 
		formatDT = "0" & CStr(dtpart)
	Else
		formatDT = CStr(dtpart)
	End If
End Function
 

Sub logit(text)
	Wscript.echo text
End Sub

QuestionANy tips for getting this to work with SQL SERVER 2005 named instances?membertradergordo6 May '09 - 11:18 
It works fine with SQL SERVER 2000 databases. I have the SQL SERVER 2005 client tools installed on my machine, and the newer SQLDMO that SHOULD work with SQL SERVER 2005. But for some reason I can't connect, I'm not sure if it's because my SQL SERVER 2005 servers are all named instances or not?
 
The code dies on the line:
oSQLServer.Connect SQL_SERVERNAME
 
It cannot connect. Seems like there must be some silly thing I'm missing...
 
I've tried using both IP & port format as well as named instance format, ie:
 
SQL_SERVERNAME = "192.168.1.7,1434"
SQL_SERVERNAME = "MyServer/ck1"
 
Both forms work fine for connecting in sql server management studio or query analyzer so I don't think that is the problem (note I know the default port is 1433, I told it to use 1434 for my named instance - so that is not an error, like I said, it works fine outside of this SQL DMO use). What else could be wrong?
 
Any tips would be greatly appreciated. I've been using similar code for years for change control, my script sends it directly to visual source safe. But now that we are finally upgrading to 2005, I'm trying to get this code to work all over again!
QuestionOrderDescending Option Wrong?memberRandy Syring27 Jan '09 - 11:32 
I needed to remove the date/time stamp that was being generated in the output. After consulting the documentation here:
 
http://msdn.microsoft.com/en-us/library/ms135191.aspx
 
It would seem that the following option is labeled wrong:
 

const SQLDMODep_OrderDescending = 131072

 
As the documentation says this is the IncludeHeader setting.
 
Removing `SQLDMODep_OrderDescending` from the options list at the bottom of the script removed the text heading from the generated files.
 
Thanks so much, this script helped me a lot!
AnswerRe: OrderDescending Option Wrong?memberozkar garcia9 Feb '09 - 4:45 
thanks for noticing that problem. I have corrected the script
Generalgood starting point, but needed workmemberfrendy glasser25 Sep '08 - 2:02 
This routine was a very good starting point. However, it would have been more effective had it worked within SQL Server Agent so that it could be a scheduled job. The changes required were too many to list here, but included destroying the objects, not using wscript, and getting rid of the stdIO output statements.
General[Message Removed]memberMojtaba Vali23 May '08 - 22:07 
Spam message removed
GeneralGreat script!memberchrelad9 May '08 - 8:07 
Man, this is just what I was looking for Smile | :)
 
Thank you very much for a well written script.
 
Perhaps now we can work on adding in logic that will run all these in the *correct* order Big Grin | :-D That's where the gold is at in my opinion.
 
Thanks again!
 
Chrelad
GeneralRe: Great script!memberozkar garcia11 May '08 - 3:48 
yes, that would be a nice feature. Let me take a look at that. There are other already working on it
 
Thanks for the feedback
GeneralHere is another snippit that scripts out constraints (for those who care)memberPunktech.com1 May '08 - 11:20 

...
 
Dim tbl
For Each tbl In oSql.Databases(database).Tables
call ScriptObjects(tbl.Keys,"KEY","Reading keys: ")
Next
 
...
 
sub ScriptKeys(list,ext,msg)
 
Dim object
StdOut.Echo ""
StdOut.Echo msg
 
'set the scripting options
dim options
options = SQLDMOScript_Indexes _
OR SQLDMOScript_Drops _
OR SQLDMOScript_IncludeIfNotExists _
OR SQLDMOScript_OwnerQualify _
OR SQLDMOScript_PrimaryObject _
Or SQLDMODep_Children _
Or SQLDMOScript_DRI_AllConstraints _
Or SQLDMODep_OrderDescending _
Or SQLDMOScript_ObjectPermissions _
Or SQLDMOScript_ToFileOnly _
OR SQLDMOScript2_NoCollation _
OR SQLDMOScript_Triggers
 
For Each object In list
StdOut.Echo object.Name
object.Script options, folder + "\" + object.Name + "." + ext
Next
 
end sub

QuestionRe: Here is another snippit that scripts out constraints (for those who care)memberchrelad9 May '08 - 7:52 
How do you use it? Does it go inside the script on this page? If so, where does it go inside the script?
 
This looks very nice, and I'd love to use it!
 
D'Oh! | :doh:
NewsRe: Here is another snippit that scripts out constraints (for those who care)memberchrelad9 May '08 - 8:06 
Figured it out... I think Smile | :)
 
Here's what I've got, and it seems to work:
 
' 0g_SqlExtract.vbs - Extracs the SQL objects from a SQL server database to a script file
'
' Author: ogarcia (og-bit.com)
' Date : 10/11/2006
' Usage: cscript 0g_sqlextract.vbs [server or sql instance name] [database] [output folder] [username] [password]
'
'
'
 
Option Explicit
 
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
dim connString
dim database
dim folder
dim oSql:
 
const SQLDMODep_Children = 262144 'List all Microsoft® SQL Server™ components that depend on the referenced SQL Server component.
const SQLDMODep_OrderDescending = 131072 'Apply descending order to returned list.
const SQLDMOScript_DRI_AllConstraints = 520093696 'SQLDMOScript_DRI_Checks, SQLDMOScript_DRI_Defaults, SQLDMOScript_DRI_ForeignKeys, SQLDMOScript_DRI_PrimaryKey, and SQLDMOScript_DRI_UniqueKeys
const SQLDMOScript_ToFileOnly = 64 'output file
const SQLDMOScript_OwnerQualify = 262144 'object owner
const SQLDMOScript_PrimaryObject = 4 'Generate Transact-SQL creating the referenced component.
const SQLDMOScript_ObjectPermissions = 2 'Include Transact-SQL privilege defining statements when scripting database objects.
const SQLDMOScript_IncludeIfNotExists =4096 'if exists
const SQLDMOScript_Indexes = 73736 'indexs
const SQLDMOScript2_NoCollation = 8388608 'no collation
const SQLDMOScript_Triggers = 16 'triggers
const SQLDMOScript_Drops = 1 'Generate Transact-SQL to remove the referenced component. Script tests for existence prior attempt to remove component.
 
Main
 
sub Main

'get the parameter list
dim objArgs: Set objArgs = WScript.Arguments
 
if objArgs.Count > 2 then
connString = objArgs(0) 'connection
database = objArgs(1) 'database
folder = objArgs(2) 'output folder

dim user
dim pw
dim tbl

Set oSql = WScript.CreateObject("SQLDMO.SQLServer2")

if objArgs.Count > 4 then
user = objArgs(3)
pw = objArgs(4)
StdOut.Echo "SQL Authentication - Connection to database"
oSql.LoginSecure = False 'sql authentication
oSql.Connect connString ,user,pw
else
StdOut.Echo "windows Authentication - Connection to database"
oSql.LoginSecure = True 'windows authentication
oSql.Connect connString
end if

call ScriptObjects(oSql.Databases(database).Tables,"TAB","Reading tables: ")
call ScriptObjects(oSql.Databases(database).Views,"VIW","Reading views: ")
call ScriptObjects(oSql.Databases(database).StoredProcedures,"PRC","Reading procedures: ")
call ScriptObjects(oSql.Databases(database).UserDefinedFunctions,"UDF","Reading functions: ")
for each tbl in oSql.Databases(database).Tables
call ScriptKeys(tbl.Keys, "KEY", "Reading keys: ")
next

oSql.Disconnect

else
StdOut.Echo "Usage: sqlextract.vbs [server or sql instance name] [database] [output folder]"
end if
 
set oSql = nothing

if err.Description <> "" then
StdOut.Echo err.Description
end if
 
end sub
 

'ScriptObjects
'
'scrips all the objects
'
' list - collection
' ext - extension name to use
' msg - message to display
sub ScriptObjects(list,ext,msg)
 

Dim object
StdOut.Echo ""
StdOut.Echo msg

'set the scripting options
dim options
options = SQLDMOScript_Indexes _
OR SQLDMOScript_Drops _
OR SQLDMOScript_IncludeIfNotExists _
OR SQLDMOScript_OwnerQualify _
OR SQLDMOScript_PrimaryObject _
Or SQLDMODep_Children _
Or SQLDMOScript_DRI_AllConstraints _
Or SQLDMODep_OrderDescending _
Or SQLDMOScript_ObjectPermissions _
Or SQLDMOScript_ToFileOnly _
OR SQLDMOScript2_NoCollation _
OR SQLDMOScript_Triggers

For Each object In list

If Not object.SystemObject Then
StdOut.Echo object.Name
object.Script options, folder + "\" + object.Owner + "." + object.Name + "." + ext
End If

Next

end sub
 
sub ScriptKeys(list,ext,msg)
 
Dim object
StdOut.Echo ""
StdOut.Echo msg
 
'set the scripting options
dim options
options = SQLDMOScript_Indexes _
OR SQLDMOScript_Drops _
OR SQLDMOScript_IncludeIfNotExists _
OR SQLDMOScript_OwnerQualify _
OR SQLDMOScript_PrimaryObject _
Or SQLDMODep_Children _
Or SQLDMOScript_DRI_AllConstraints _
Or SQLDMODep_OrderDescending _
Or SQLDMOScript_ObjectPermissions _
Or SQLDMOScript_ToFileOnly _
OR SQLDMOScript2_NoCollation _
OR SQLDMOScript_Triggers
 
For Each object In list
StdOut.Echo object.Name
object.Script options, folder + "\" + object.Name + "." + ext
Next
 
end sub

GeneralRe: Here is another snippit that scripts out constraints (for those who care)memberozkar garcia11 May '08 - 4:38 
Thanks for the feedback.
 
To generate all the keys for the table, I would just add another option to the ScriptObjects subroutine. I would add the following:
 
In the constants declaration, add the following:
 
Const SQLDMOScript_DRI_All = 532676608
 
In the subroutine, add this additional option;
'set the scripting options
dim options
options = SQLDMOScript_Indexes _
OR SQLDMOScript_Drops _
OR SQLDMOScript_IncludeIfNotExists _
OR SQLDMOScript_OwnerQualify _
OR SQLDMOScript_PrimaryObject _
Or SQLDMODep_Children _
Or SQLDMOScript_DRI_AllConstraints _
Or SQLDMODep_OrderDescending _
Or SQLDMOScript_ObjectPermissions _
Or SQLDMOScript_ToFileOnly _
OR SQLDMOScript2_NoCollation _
OR SQLDMOScript_Triggers _
OR SQLDMOScript_DRI_All 'THIS IS NEW
 
The advantage of this is that the table definitions and keys will be in one file.
 
I will update the script to reflect this change.
GeneralAwesome script!membermaniatisa23 Apr '07 - 9:50 
Thanks... I was looking for a basic script that I could expand to sort of "automate" the writing of masses of stored procedures and C# code. Ok, so it's not the magic wand that will do everything... but you have saved me weeks of hand-coding stuff. Now all I have to do is verify and modify!
GeneralRe: Awesome script!membertoxaq10 May '07 - 15:15 
I agree. I'll certainly be using this in the future! Thanks.
GeneralRe: Awesome script!memberozkar23 Oct '07 - 8:39 
I am glad it can help someone.
 
thanks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 10 Feb 2009
Article Copyright 2006 by ozkar garcia
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid