sql - 使用SMO从SQL脚本出单个对象

标签 sql sql-server powershell smo

对于我的工作,我经常不得不从Microsoft SQL 2008服务器中编写一个包含所有键,约束和触发器的表的脚本(基本上是用于重新创建表的完整脚本),我还必须对过程和触发器执行此操作。
我现在要做的是打开SSMS,右键单击该对象,然后选择要编写的脚本,然后选择将其编写成文件。因此,如果我要执行3个过程,10个表和1个触发器,则最终要执行14次。
我想要的是一个Powershell脚本,我可以向其中提供对象列表,然后再使用SMO将每个脚本写到单个文件中。

谢谢您的帮助

最佳答案

这是我必须在编写数据库脚本时使用的PowerShell功能。仅对所需的对象编写脚本就应该很容易进行修改。

function SQL-Script-Database
{
    <#
    .SYNOPSIS
    Script all database objects for the given database.

    .DESCRIPTION
    This  function scripts all database objects  (i.e.: tables,  views, stored
    procedures,  and user defined functions) for the specified database on the
    the given server\instance. It creates a subdirectory per object type under 
    the path specified.

    .PARAMETER savePath
    The root path where to save object definitions.

    .PARAMETER database
    The database to script (default = $global:DatabaseName)

    .PARAMETER DatabaseServer 
    The database server to be used (default: $global:DatabaseServer).

    .PARAMETER InstanceName 
    The instance name to be used (default: $global:InstanceName).

    .EXAMPLE
    SQL-Script-Database c:\temp AOIDB
    #>

    param (
        [parameter(Mandatory = $true)][string] $savePath,
        [parameter(Mandatory = $false)][string] $database = $global:DatabaseName,
        [parameter(Mandatory = $false)][string] $DatabaseServer = $global:DatabaseServer,
        [parameter(Mandatory = $false)][string] $InstanceName = $global:InstanceName
    )

    try
    {
        if (!$DatabaseServer -or !$InstanceName)
            { throw "`$DatabaseServer or `$InstanceName variable is not properly initialized" }

        $ServerInstance = SQL-Get-Server-Instance $DatabaseServer $InstanceName

        [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null

        $s = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)
        $db = $s.databases[$database]

        $objects = $db.Tables
        $objects += $db.Views
        $objects += $db.StoredProcedures
        $objects += $db.UserDefinedFunctions

        $scripter = New-Object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)

        $scripter.Options.AnsiFile = $true
        $scripter.Options.IncludeHeaders = $false
        $scripter.Options.ScriptOwner = $false
        $scripter.Options.AppendToFile = $false
        $scripter.Options.AllowSystemobjects = $false
        $scripter.Options.ScriptDrops = $false
        $scripter.Options.WithDependencies = $false
        $scripter.Options.SchemaQualify = $false
        $scripter.Options.SchemaQualifyForeignKeysReferences = $false
        $scripter.Options.ScriptBatchTerminator = $false

        $scripter.Options.Indexes = $true
        $scripter.Options.ClusteredIndexes = $true
        $scripter.Options.NonClusteredIndexes = $true
        $scripter.Options.NoCollation = $true

        $scripter.Options.DriAll = $true
        $scripter.Options.DriIncludeSystemNames = $false

        $scripter.Options.ToFileOnly = $true
        $scripter.Options.Permissions = $true

        foreach ($o in $objects | where {!($_.IsSystemObject)}) 
        {
            $typeFolder=$o.GetType().Name 

            if (!(Test-Path -Path "$savepath\$typeFolder")) 
                { New-Item -Type Directory -name "$typeFolder"-path "$savePath" | Out-Null }

            $file = $o -replace "\[|\]"
            $file = $file.Replace("dbo.", "")

            $scripter.Options.FileName = "$savePath\$typeFolder\$file.sql"
            $scripter.Script($o)
        }
    }

    catch
    {
        Util-Log-Error "`t`t$($MyInvocation.InvocationName): $_"
    }
}

关于sql - 使用SMO从SQL脚本出单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12948678/

相关文章:

PHP "str_replace"在某些情况下无法正常工作?

javascript - 从mssql模块中的异步函数返回数据

powershell - 如何在 PowerShell 中为脚本提供参数属性?

powershell - 将WMI日期更改为仅DATE

xml - 直接访问 XML 中的键值对

mysql - SQL 查询性能虽然相同但有所不同

SQL Server 2008 似乎为每个查询选择 PK 索引,即使似乎存在更好的索引

sql-server - 无法在 Linux RHEL 7 中创建 SSISDB 目录

mysql - SQL Server : Group by Replace NULL

mysql - SQL 中的数量偏移