기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
SQL Server 데이터베이스 객체 내보내기
오프라인 소스의 경우 소스 데이터베이스 객체를 설명하는 내보낸 스크립트 파일을 업로드합니다. 사용 가능한 도구를 사용하여 내보낼 수 있습니다. 다음 탭은 SQL Server Management Studio(SSMS)와 SQL Server Management Objects(SMO)의 두 가지 접근 방식을 설명합니다.
- SSMS
-
SSMS의 객체 탐색기에서 내보낼 데이터베이스를 마우스 오른쪽 버튼으로 클릭합니다. 작업을 선택한 다음 스크립트 생성을 선택합니다.
스크립트 파일로 저장을 선택합니다.
생성할 파일에서 객체당 스크립트 파일 하나를 선택하여 각 데이터베이스 객체에 대해 별도의
.sql파일을 생성합니다.디렉터리 이름에 출력 파일의 디렉터리 경로를 입력합니다. 데이터베이스와 이름이 같은 디렉터리를 생성하는 것이 좋습니다.
다른 이름으로 저장에서 유니코드 텍스트를 선택합니다.
고급을 선택하여 고급 스크립팅 옵션 대화 상자를 엽니다.
다음 표에 따라 옵션을 설정합니다.
확인을 선택한 후 다음을 선택하여 요약을 검토합니다.
다음을 선택하여 스크립트를 생성합니다.
마침을 선택하여 마법사를 닫습니다.
고급 스크립팅 옵션
고급 스크립팅 옵션 대화 상자에서 다음 옵션을 설정합니다.
일반 옵션 옵션 값 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 이상
SqlServerPowerShell 모듈(를 사용하여 설치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) } }