스크립팅

적용 대상:SQL ServerAzure SQL DatabaseAzure SQL Managed InstanceAzure Synapse Analytics

SMO의 스크립팅은 개체 및 해당 자식 개체 또는 개별 개체의 Script 메서드에 의해 Scripter 제어됩니다. 이 개체는 Scripter Microsoft SQL Server 인스턴스의 개체에 대한 종속성 관계의 매핑을 제어합니다.

개체와 해당 자식 개체를 Scripter 사용한 고급 스크립팅은 다음 세 단계 프로세스입니다.

  1. 검색

  2. 목록 생성

  3. 스크립트 생성

검색 단계에서는 개체를 DependencyWalker 사용합니다. URN 개체 목록이 지정된 경우 개체 DiscoverDependenciesDependencyWalker 메서드는 URN 목록의 개체에 대한 개체를 반환 DependencyTree 합니다. 부울 fParents 매개 변수는 지정된 개체의 부모 또는 자식을 검색할지 여부를 선택하는 데 사용됩니다. 이 단계에서 종속성 트리를 수정할 수 있습니다.

목록 생성 단계에서 트리가 전달되고 결과 목록이 반환됩니다. 이 개체 목록은 스크립팅 순서이며 조작할 수 있습니다.

목록 생성 단계에서는 WalkDependencies 메서드를 사용하여 DependencyTree를 반환합니다. 이 DependencyTree 단계에서 수정할 수 있습니다.

세 번째 및 마지막 단계에서는 지정된 목록 및 스크립팅 옵션을 사용하여 스크립트가 생성됩니다. 결과는 시스템 개체로 StringCollection 반환됩니다. 이 단계에서는 DependencyTree 개체의 항목 컬렉션과 NumberOfSiblingsFirstChild와 같은 속성으로부터 종속 개체 이름이 추출됩니다.

제공된 코드 예제를 사용하려면 프로그래밍 환경, 프로그래밍 템플릿 및 애플리케이션을 만들 프로그래밍 언어를 선택해야 합니다. 자세한 내용은 Visual Studio .NET에서 Visual C# SMO 프로젝트 만들기를 참조하세요.

이 코드 예제에는 System.Collections.Specialized 네임스페이스에 대한 Imports 문이 필요합니다. 애플리케이션의 선언 앞에 다른 Imports 문과 함께 삽입합니다.

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 AdventureWorks2022.  
  
CD Databases\AdventureWorks2022\Tables  
  
foreach ($Item in Get-ChildItem)  
 {    
 $scrp.Script($Item)  
 }