View a markdown version of this page

SQL Server 데이터베이스 객체 내보내기 - AWS 데이터베이스 마이그레이션 서비스

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

SQL Server 데이터베이스 객체 내보내기

오프라인 소스의 경우 소스 데이터베이스 객체를 설명하는 내보낸 스크립트 파일을 업로드합니다. 사용 가능한 도구를 사용하여 내보낼 수 있습니다. 다음 탭은 SQL Server Management Studio(SSMS)와 SQL Server Management Objects(SMO)의 두 가지 접근 방식을 설명합니다.

SSMS
  1. SSMS의 객체 탐색기에서 내보낼 데이터베이스를 마우스 오른쪽 버튼으로 클릭합니다. 작업을 선택한 다음 스크립트 생성을 선택합니다.

  2. 스크립트 파일로 저장을 선택합니다.

  3. 생성할 파일에서 객체당 스크립트 파일 하나를 선택하여 각 데이터베이스 객체에 대해 별도의 .sql 파일을 생성합니다.

  4. 디렉터리 이름에 출력 파일의 디렉터리 경로를 입력합니다. 데이터베이스와 이름이 같은 디렉터리를 생성하는 것이 좋습니다.

  5. 다른 이름으로 저장에서 유니코드 텍스트를 선택합니다.

  6. 고급을 선택하여 고급 스크립팅 옵션 대화 상자를 엽니다.

  7. 다음 표에 따라 옵션을 설정합니다.

  8. 확인을 선택한 후 다음을 선택하여 요약을 검토합니다.

  9. 다음을 선택하여 스크립트를 생성합니다.

  10. 마침을 선택하여 마법사를 닫습니다.

고급 스크립팅 옵션

고급 스크립팅 옵션 대화 상자에서 다음 옵션을 설정합니다.

일반 옵션
옵션
ANSI 패딩False
파일에 추가False
객체 존재 확인False
오류 시 스크립팅 계속True
UDDTs 기본 유형으로 변환False
종속 객체에 대한 스크립트 생성True
설명 헤더 포함False
스크립팅 파라미터 헤더 포함False
시스템 제약 조건 이름 포함False
스키마 검증 객체 이름True
스크립트 바인딩False
스크립트 데이터 정렬True
스크립트 기본값True
스크립트 삭제 및 생성스크립트 CREATE
스크립트 확장 속성True
스크립트 로그인False
스크립트 객체 수준 권한False
스크립트 소유자False
스크립트 통계통계를 스크립팅하지 않음
스크립트 사용 데이터베이스True
스크립트할 데이터 유형스키마만
테이블/보기 옵션
옵션
스크립트 변경 사항 추적False
스크립트 검사 제약 조건True
스크립트 데이터 압축 옵션False
스크립트 외래 키True
스크립트 전체 텍스트 인덱스True
스크립트 인덱스True
스크립트 기본 키True
스크립트 트리거True
스크립트 고유 키True
SMO

SQL Server Management Objects(SMO)는 SQL Server를 프로그래밍 방식으로 관리하기 위한 .NET API입니다. SMO를 PowerShell 또는 C#과 함께 사용하여 데이터베이스 객체를 스크립팅하고 오프라인 소스와 함께 사용할 DDL 파일을 생성할 수 있습니다.

사전 조건

  • Windows PowerShell 5.1 이상 또는 PowerShell 7 이상

  • SqlServer PowerShell 모듈(를 사용하여 설치Install-Module SqlServer)

  • .NET Framework 4.6.2 이상 또는 교차 플랫폼의 경우 .NET 6 이상

키 스크립팅 구성

SMO를 사용하여 오프라인 소스에 대한 스크립트를 내보내는 경우 다음 스크립팅 옵션을 구성합니다.

필수 SMO 스크립팅 옵션
옵션
ToFileOnlyTrue
Encoding유니코드
AppendToFileFalse
IncludeHeadersTrue
IncludeDatabaseContextTrue
SchemaQualifyTrue
AnsiPaddingTrue
DefaultTrue
DriAllTrue
IndexesTrue
TriggersTrue
FullTextIndexesTrue
ExtendedPropertiesTrue
ScriptDataCompressionTrue
ScriptDropsFalse
IncludeIfNotExistsFalse
WithDependenciesFalse
NoCollationTrue
PermissionsFalse
ContinueScriptingOnErrorTrue

PowerShell 스크립트 예제

다음 스크립트는 모든 데이터베이스 객체를 개별 .sql 파일로 내보냅니다. 각 파일에는 단일 데이터베이스 객체에 대한 명령CREATE문이 하나씩 포함되어 있습니다.

# Export SQL Server database objects using SMO # Usage: .\Export-Database.ps1 -Database "MyDB" -OutputDir "C:\export\MyDB" param( [string] $ServerInstance = "localhost", # SQL Server instance name [Parameter(Mandatory)] [string] $Database, # Database to export [Parameter(Mandatory)] [string] $OutputDir, # Output directory for .sql files [switch] $TrustServerCertificate # Skip certificate validation ) $ErrorActionPreference = "Stop" # Load the SqlServer module (includes SMO assemblies) Import-Module SqlServer -ErrorAction Stop # Connect to SQL Server $srv = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance) $srv.ConnectionContext.EncryptConnection = $true if ($TrustServerCertificate) { $srv.ConnectionContext.TrustServerCertificate = $true } # Get the database $db = $srv.Databases[$Database] if (-not $db) { Write-Error "Database '$Database' not found."; exit 1 } if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null } # Configure scripting options for offline source compatibility $scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter($srv) $opts = $scripter.Options $opts.ToFileOnly = $true # Write directly to files $opts.Encoding = [System.Text.Encoding]::Unicode # Unicode encoding $opts.AppendToFile = $false # One object per file $opts.IncludeHeaders = $true # Add descriptive headers $opts.IncludeDatabaseContext = $true # Add USE [database] statement $opts.SchemaQualify = $true # Use schema.object format $opts.AnsiPadding = $true # Include ANSI_PADDING settings $opts.Default = $true # Include default constraints $opts.DriAll = $true # Include all constraints and keys $opts.Indexes = $true # Include indexes $opts.Triggers = $true # Include triggers $opts.FullTextIndexes = $true # Include full-text indexes $opts.ExtendedProperties = $true # Include extended properties $opts.ScriptDataCompression = $true # Include data compression settings $opts.ScriptDrops = $false # CREATE only, no DROP statements $opts.IncludeIfNotExists = $false # No IF NOT EXISTS wrapper $opts.WithDependencies = $false # Do not script dependent objects $opts.NoCollation = $true # Omit collation clauses $opts.Permissions = $false # Omit permissions $opts.ContinueScriptingOnError = $true # Skip errors, continue with next object # Define which object types to export $collections = [ordered]@{ "Schemas" = "Schema" "Tables" = "Table" "Views" = "View" "StoredProcedures" = "StoredProcedure" "UserDefinedFunctions" = "UserDefinedFunction" "Sequences" = "Sequence" "Synonyms" = "Synonym" "UserDefinedDataTypes" = "UserDefinedDataType" "UserDefinedTableTypes" = "UserDefinedTableType" "UserDefinedTypes" = "UserDefinedType" "UserDefinedAggregates" = "UserDefinedAggregate" "XmlSchemaCollections" = "XmlSchemaCollection" "Rules" = "Rule" "Defaults" = "Default" "PartitionSchemes" = "PartitionScheme" "PartitionFunctions" = "PartitionFunction" "Assemblies" = "SqlAssembly" "FullTextCatalogs" = "FullTextCatalog" "FullTextStopLists" = "FullTextStopList" "SearchPropertyLists" = "SearchPropertyList" "SecurityPolicies" = "SecurityPolicy" "ExternalDataSources" = "ExternalDataSource" "ExternalFileFormats" = "ExternalFileFormat" } # System schemas to skip $sysSchemas = 'dbo','guest','INFORMATION_SCHEMA','sys', 'db_owner','db_accessadmin','db_securityadmin','db_ddladmin', 'db_backupoperator','db_datareader','db_datawriter', 'db_denydatareader','db_denydatawriter' # Export the CREATE DATABASE statement $dbScripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter($srv) $dbScripter.Options.ToFileOnly = $true $dbScripter.Options.Encoding = [System.Text.Encoding]::Unicode $dbScripter.Options.IncludeDatabaseContext = $true $dbScripter.Options.FileName = Join-Path $OutputDir "$Database.Database.sql" $dbScripter.Script($db) # Export each object to a separate .sql file foreach ($colName in $collections.Keys) { $col = $db.$colName if (-not $col -or $col.Count -eq 0) { continue } foreach ($obj in $col) { # Skip system objects if ($obj.PSObject.Properties['IsSystemObject'] -and $obj.IsSystemObject) { continue } if ($colName -eq "Schemas" -and $obj.Name -in $sysSchemas) { continue } # Build the output file name: schema.objectname.type.sql $schema = if ($obj.PSObject.Properties['Schema']) { $obj.Schema } else { "" } $safeName = $obj.Name -replace '[\\/:*?"<>|]', '_' $fileName = if ($schema) { "$schema.$safeName.$($collections[$colName]).sql" } else { "$safeName.$($collections[$colName]).sql" } $opts.FileName = Join-Path $OutputDir $fileName $scripter.Script($obj) } }