How to automate script generation using SMO in SQL Server?

前端 未结 3 870
粉色の甜心
粉色の甜心 2021-01-01 02:18

I would like to automate script generation (in SSMS --> Tasks --> Generate Scripts) in SSMS 2008. I have read that SQL Server 2008 does not support Database Publishing Wizar

3条回答
  •  萌比男神i
    2021-01-01 02:27

    There a few ways of scripting all objects in database, but one of the easiest is to you the SMO tranfer class. Here's some PowerShell code to script out all objects:

    add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
    add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
    add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
    
    $sourceSrv = "$env:computername\sql2k8"
    $sourceDb = "Northwind"
    
    $server =  new-object ("Microsoft.SqlServer.Management.Smo.Server") $sourceSrv
    $db = $server.Databases[$sourceDb]
    
    $transfer = new-object ("Microsoft.SqlServer.Management.Smo.Transfer") $db
    $transfer.CopyAllObjects = $true
    $transfer.DropDestinationObjectsFirst = $true
    $transfer.CopySchema = $true
    $transfer.Options.IncludeIfNotExists = $true
    
    $transfer.ScriptTransfer()
    

提交回复
热议问题