CREATE procedure dmoScriptDatabase
  @serverName varchar(30),
  @databaseName varchar(30),
  @outputPath varchar(255) = 'c:\',
  @style tinyint = 0
as
declare @objectName varchar(255)
declare @dmoServer int
declare @cmd varchar(255)

/* uses a trusted osql connetion back to the admin database to create an output file
    containing the CREATE DATABASE statement for the specified database */
select @cmd = 'osql -U sa -E -S ' + @@SERVERNAME + ' -Q "admin.dbo.ScriptCreateDatabase '+ 
                        @serverName +', ' + @databaseName + '" -o '+ @outputPath + @serverName + '_Databases_' + @databaseName +'.sql -h-1 -w2000' 
exec master..xp_cmdshell @cmd 

/* use Integrated Security for the OLE process */
exec dmoConnectServer @serverName, @dmoServer OUT

if @dmoServer > 0
  begin
    /* each table object has several collections to process */
    exec dmoScriptTables @dmoServer, @serverName, @databaseName, @outputPath, @style

    /* other database objects can use a generic script generator */
    exec dmoScriptDatabaseCollection @dmoServer, @serverName,  @databaseName, 'Users', @outputPath, @style
    exec dmoScriptDatabaseCollection @dmoServer, @serverName,  @databaseName, 'DatabaseRoles', @outputPath, @style
    exec dmoScriptDatabaseCollection @dmoServer, @serverName, @databaseName, 'StoredProcedures', @outputPath, @style
    exec dmoScriptDatabaseCollection @dmoServer, @serverName, @databaseName, 'Views', @outputPath, @style
    exec dmoScriptDatabaseCollection @dmoServer, @serverName, @databaseName, 'Rules', @outputPath, @style 
    exec dmoScriptDatabaseCollection @dmoServer, @serverName,  @databaseName, 'Defaults', @outputPath, @style
    exec dmoScriptDatabaseCollection @dmoServer, @serverName, @databaseName, 'UserDefinedDatatypes', @outputPath, @style 

    /* a little clean up */
    exec dmoDisconnectServer @dmoServer
  end