如何使用包含模式名称的powershell编写数据库中的过程

时间:2014-04-15 14:11:53

标签: powershell

您好我有以下电源shell代码来编写数据库中的所有过程。所有这些程序都在模式dbo中。但是我得到了一些用模式名称编写脚本的过程,而其他的脚本没有模式名称。谁能告诉我原因。

# Configuration data
[string] $server   = "Demo123";          # SQL Server Instance
[string] $database = "Test212";      # Database with the tables to script out.
[string] $folder   = "C:\Testing";          # Path to export to

# Reference to SMO
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO');



$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $server;
#This sets the connection to mixed-mode authentication 
$srv.ConnectionContext.LoginSecure=$false; 


#This sets the login name 
$srv.ConnectionContext.set_Login("sa"); 

#This sets the password 
$srv.ConnectionContext.set_Password("Database123")  

$db = $srv.Databases[$database];

# Configuration for scripting options: Which related objects should also be scripted?
$so = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions;
$so.DriAllConstraints = $true;
$so.DriAllKeys        = $true;
$so.DriClustered      = $true;
$so.DriDefaults       = $true;
$so.DriIndexes        = $true;
$so.DriNonClustered   = $true;
$so.DriPrimaryKey     = $true;
$so.DriUniqueKeys     = $true;

$so.AnsiFile          = $true;
$so.ClusteredIndexes  = $true;
$so.IncludeHeaders    = $true;
$so.Indexes           = $true;
$so.SchemaQualify     = $true;
$so.Triggers          = $true;
$so.XmlIndexes        = $true;


$loop = 0;
$script = "";
$spBody = "";
$head  = "";
$filename="";
foreach ($sp in $db.StoredProcedures) 
{
   if (!$sp.IsSystemObject){        


        $script="SET ANSI_NULLS ON"
        $script = $script + [Environment]::NewLine + "GO" + [Environment]::NewLine + "SET QUOTED_IDENTIFIER ON" + [Environment]::NewLine + "GO" + [Environment]::NewLine

        $script =$script +  [string]::Format("IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[{0}].[{1}]') AND type in (N'P', N'PC'))", $sp.Schema, $sp.Name);
        $script = $script + [Environment]::NewLine + "DROP PROCEDURE " + "[" + $sp.Schema + "]" + "." + "[" + $sp.Name + "]" + [Environment]::NewLine;  
        $script = $script + "GO"+ [Environment]::NewLine

         #To add set quoted identifier on


        $head = $sp.TextHeader 

        $script = $script + $head;
        $spBody =  $sp.TextBody 

        $script = $script + $spBody.Trim() + [Environment]::NewLine + "GO" + [Environment]::NewLine ;

         $script | out-File D:\Test\Scripts.sql -Append


        $loop++;







        Write-Output($loop);
        Write-Output (": SP " + $sp.Name);

   }}


Write-Output ((Get-Date -format yyyy-MM-dd_HH-mm-ss) + ": Finished --- Total SPs : " + ($loop));

0 个答案:

没有答案