Microsoft Windows PowerShell and SQL Server 2005 SMO - Part 9October 3, 2007 Using PowerShell and SMO to Generate an SQL Server ScriptPart 1 and Part 2 of this series discussed Power Shell installation and simple SMO, WMI cmdlets. Part 3 covered how to script PowerShell and connect to SQL Server. Part 4 explained how to use a PowerShell script to loop through the content of a file and connect to different servers. Part 5 examined creating a SQL Server database using PowerShell and SMO. Part 6 talked about backing up a SQL Server database using PowerShell and SMO. Part 7 illustrated how to list all of the objects in a database and part 8 demonstrated how to list all of the properties of the objects in a database using PowerShell and SMO. This installment of the series illustrates how to use PowerShell in conjunction with SMO to Generate an SQL Server Script. Generating SQL Server Scripts is an essential task for SQL Server Database administrators and developers. Method 1 Lets assume that we would like to generate a Create Database script for the AdventureWorks database from the server HOME\SQLEXPRESS. Execute the following cmdlets as shown below. [Fig 1.1] [reflection.assembly]::LoadWithPartialName
Click for larger image This would generate a Create Database script for the AdventureWorks database as shown below. [Refer Fig 1.2] CREATE DATABASE [AdventureWorks] ON PRIMARY ( NAME = N'AdventureWorks_Data',
Click for larger image Method 2 Lets assume that we want to generate a script for all of the tables in the AdventureWorks database from the HOME\SQLEXPRESS server. Execute the following cmdlets as shown below. [Fig 1.3]
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$MyScripter=new-object ("Microsoft.SqlServer.Management.Smo.Scripter")
$srv=New-Object "Microsoft.SqlServer.Management.Smo.Server" "HOME\SQLEXPRESS"
$MyScripter.Server=$srv
$MyScripter.Script($srv.Databases["adventureworks"].tables)
This generates CREATE TABLE scripts for all of the tables in the AdventureWorks database from the server HOME\SQLEXPRESS. Execute the following cmdlets as shown below. [Fig 1.4]
.....
.....
CREATE TABLE [Sales].[SpecialOffer](
[SpecialOfferID] [int] IDENTITY(1,1) NOT NULL,
[Description] [nvarchar](255) COLLATE Latin1_General_CI_AS NOT NULL,
[DiscountPct] [smallmoney] NOT NULL,
[Type] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[Category] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[MinQty] [int] NOT NULL,
[MaxQty] [int] NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[SpecialOfferProduct](
[SpecialOfferID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[Store](
[CustomerID] [int] NOT NULL,
[Name] [dbo].[Name] NOT NULL,
[SalesPersonID] [int] NULL,
[Demographics] [xml](CONTENT [Sales].[StoreSurveySchemaCollection]) NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [Sales].[StoreContact](
[CustomerID] [int] NOT NULL,
[ContactID] [int] NOT NULL,
[ContactTypeID] [int] NOT NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY]
......
......
Method 3 Scripting SQL Server database and its objects comes with many options. These options can be altered by turning the available flags on and off. Execute the following cmdlets to see all of the available options in scripting. [Refer Fig 1.5]
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$MyScripter=new-object ("Microsoft.SqlServer.Management.Smo.Scripter")
$srv=New-Object "Microsoft.SqlServer.Management.Smo.Server" "HOME\SQLEXPRESS"
$MyScripter.Server=$srv
$so=$MyScripter.Options
$so
This displays all of the scripting options available that can be altered as shown below. [Refer Fig 1.6] FileName : Encoding : System.Text.UnicodeEncoding DriWithNoCheck : False ScriptDrops : False TargetServerVersion : Version80 AnsiFile : False AppendToFile : False ToFileOnly : False SchemaQualify : True IncludeHeaders : False IncludeIfNotExists : False WithDependencies : False DriPrimaryKey : False DriForeignKeys : False DriUniqueKeys : False DriClustered : False DriNonClustered : False DriChecks : False DriDefaults : False Triggers : False Bindings : False NoFileGroup : False NoCollation : False ContinueScriptingOnError : False Permissions : False AllowSystemObjects : True NoIdentities : False ConvertUserDefinedDataTypesToBaseType : False TimestampToBinary : False AnsiPadding : False ExtendedProperties : False DdlHeaderOnly : False DdlBodyOnly : False NoViewColumns : False Statistics : True SchemaQualifyForeignKeysReferences : False ClusteredIndexes : False NonClusteredIndexes : False AgentAlertJob : False AgentJobId : False AgentNotify : False LoginSid : False FullTextIndexes : False NoCommandTerminator : False NoIndexPartitioningSchemes : False NoTablePartitioningSchemes : False IncludeDatabaseContext : False FullTextCatalogs : False NoXmlNamespaces : False NoAssemblies : False PrimaryObject : True DriIncludeSystemNames : False Default : True XmlIndexes : False OptimizerData : False NoExecuteAs : False EnforceScriptingOptions : False NoMailProfileAccounts : False NoMailProfilePrincipals : False Indexes : False DriIndexes : False DriAllKeys : False DriAllConstraints : False DriAll : False
Now lets try to save the generated Create Database script on to a file using the Scripting option. Execute the cmdlets shown below. [Refer Fig 1.7]
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$MyScripter=new-object ("Microsoft.SqlServer.Management.Smo.Scripter")
$srv=New-Object "Microsoft.SqlServer.Management.Smo.Server" "HOME\SQLEXPRESS"
$MyScripter.Server=$srv
$so=$MyScripter.Options
$so.FileName="C:\MyDatabaseScript.sql"
$MyScripter.Script($srv.Databases["adventureworks"])
This would generate the Create Database script on to the file C:\MyDatabaseScript.sql, as shown in Fig 1.8 and Fig 1.8.
ConclusionPart 9 of this article series illustrated how to use PowerShell and SMO to generate a script for database and tables. It also illustrated how to use scripting options to write to a file. Part 10 will discuss more about scripting options and how to create PowerShell scripts to generate SQL Server scripts by passing parameters. |