Поделиться через


Скриптинг

Скрипты в SMO управляются объектом и его дочерними Scripter объектами или методом Script для отдельных объектов. Объект Scripter управляет сопоставлением связей зависимостей для объектов на экземпляре MicrosoftSQL Server.

Расширенный скрипт с помощью Scripter объекта и его дочерних объектов — это три этапа:

  1. Открытие

  2. Создание списка

  3. Создание скриптов

Этап обнаружения использует DependencyWalker объект. Учитывая список объектов URN, DiscoverDependencies метод DependencyWalker объекта возвращает DependencyTree объект для объектов в списке URN. Логический параметр fParents используется для выбора того, должны ли быть обнаружены родители или дочерние элементы указанного объекта. Дерево зависимостей можно изменить на этом этапе.

На этапе создания списка дерево передается и возвращается результирующий список. Этот список объектов находится в порядке скриптов и может управляться.

Этапы создания списка используют WalkDependencies метод для возврата DependencyTree. Его DependencyTree можно изменить на этом этапе.

На третьем и заключительном этапе скрипт создается с указанными параметрами списка и сценариев. Результат возвращается в виде системного StringCollection объекта. На этом этапе имена зависимых объектов извлекаются из коллекции "Элементы" объекта и свойств, таких DependencyTree как NumberOfSiblings и FirstChild.

Пример

Чтобы использовать любой приведенный пример кода, необходимо выбрать среду программирования, шаблон программирования и язык программирования, в котором будет создано приложение. Дополнительные сведения см. в статье "Создание проекта SMO Visual Basic" в Visual Studio .NET или создание проекта SMO Visual C# в Visual Studio .NET.

В этом примере кода требуется Imports инструкция для пространства имен System.Collections.Specialized. Вставьте его с другими операторами Import перед объявлениями в приложении.

Imports Microsoft.SqlServer.Management.Smo  
Imports Microsoft.SqlServer.Management.Common  
Imports System.Collections.Specialized  

Скриптирование зависимостей для базы данных в Visual Basic

В этом примере кода показано, как обнаружить зависимости и выполнить итерацию по списку, чтобы отобразить результаты.

' compile with:   
' /r:Microsoft.SqlServer.Smo.dll   
' /r:Microsoft.SqlServer.ConnectionInfo.dll   
' /r:Microsoft.SqlServer.Management.Sdk.Sfc.dll   
  
Imports Microsoft.SqlServer.Management.Smo  
Imports Microsoft.SqlServer.Management.Sdk.Sfc  
  
Public Class A  
   Public Shared Sub Main()  
      ' database name  
      Dim dbName As [String] = "AdventureWorksLT2012"   ' database name  
  
      ' Connect to the local, default instance of SQL Server.   
      Dim srv As New Server()  
  
      ' Reference the database.    
      Dim db As Database = srv.Databases(dbName)  
  
      ' Define a Scripter object and set the required scripting options.   
      Dim scrp As New Scripter(srv)  
      scrp.Options.ScriptDrops = False  
      scrp.Options.WithDependencies = True  
      scrp.Options.Indexes = True   ' To include indexes  
      scrp.Options.DriAllConstraints = True   ' to include referential constraints in the script  
  
      ' Iterate through the tables in database and script each one. Display the script.  
      For Each tb As Table In db.Tables  
         ' check if the table is not a system table  
         If tb.IsSystemObject = False Then  
            Console.WriteLine("-- Scripting for table " + tb.Name)  
  
            ' Generating script for table tb  
            Dim sc As System.Collections.Specialized.StringCollection = scrp.Script(New Urn() {tb.Urn})  
            For Each st As String In sc  
               Console.WriteLine(st)  
            Next  
            Console.WriteLine("--")  
         End If  
      Next  
   End Sub  
End Class  

Скриптирование зависимостей для базы данных в Visual C#

В этом примере кода показано, как обнаружить зависимости и выполнить итерацию по списку, чтобы отобразить результаты.

// compile with:   
// /r:Microsoft.SqlServer.Smo.dll   
// /r:Microsoft.SqlServer.ConnectionInfo.dll   
// /r:Microsoft.SqlServer.Management.Sdk.Sfc.dll   
  
using System;  
using Microsoft.SqlServer.Management.Smo;  
using Microsoft.SqlServer.Management.Sdk.Sfc;  
  
public class A {  
   public static void Main() {   
      String dbName = "AdventureWorksLT2012"; // database name  
  
      // Connect to the local, default instance of SQL Server.   
      Server srv = new Server();  
  
      // Reference the database.    
      Database db = srv.Databases[dbName];  
  
      // Define a Scripter object and set the required scripting options.   
      Scripter scrp = new Scripter(srv);  
      scrp.Options.ScriptDrops = false;  
      scrp.Options.WithDependencies = true;  
      scrp.Options.Indexes = true;   // To include indexes  
      scrp.Options.DriAllConstraints = true;   // to include referential constraints in the script  
  
      // Iterate through the tables in database and script each one. Display the script.     
      foreach (Table tb in db.Tables) {   
         // check if the table is not a system table  
         if (tb.IsSystemObject == false) {  
            Console.WriteLine("-- Scripting for table " + tb.Name);  
  
            // Generating script for table tb  
            System.Collections.Specialized.StringCollection sc = scrp.Script(new Urn[]{tb.Urn});  
            foreach (string st in sc) {  
               Console.WriteLine(st);  
            }  
            Console.WriteLine("--");  
         }  
      }   
   }  
}  

Скриптирование зависимостей для базы данных в PowerShell

В этом примере кода показано, как обнаружить зависимости и выполнить итерацию по списку, чтобы отобразить результаты.

# Set the path context to the local, default instance of SQL Server.  
CD \sql\localhost\default  
  
# Create a Scripter object and set the required scripting options.  
$scrp = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Scripter -ArgumentList (Get-Item .)  
$scrp.Options.ScriptDrops = $false  
$scrp.Options.WithDependencies = $true  
$scrp.Options.IncludeIfNotExists = $true  
  
# Set the path context to the tables in AdventureWorks2012.  
CD Databases\AdventureWorks2012\Tables  
  
foreach ($Item in Get-ChildItem)  
 {    
 $scrp.Script($Item)  
 }