Created
September 27, 2013 09:12
-
-
Save nakaji/6726011 to your computer and use it in GitHub Desktop.
全テーブルのCreate Table文を作成する(テーブル単位) ref: http://qiita.com/nakaji/items/91aa1986ba68232e6129
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | |
$serverName = "localhost" | |
$databaseName = "AdventureWorks" | |
$scriptDir = "D:\テーブル" | |
if (Test-Path $scriptDir) { | |
#追記するので既にファイルがある場合は出力ファイルを削除する | |
Remove-Item "$scriptDir\*" | |
}else{ | |
#出力先ディレクトリがない場合は作成 | |
mkdir $scriptDir | |
} | |
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($serverName) | |
$db = $server.Databases[$databaseName] | |
$scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter($server) | |
#出力するスクリプトの設定 | |
$scripter.Options.Indexes = $true #インデックスを含める | |
$scripter.Options.ClusteredIndexes = $true #クラスター化インデックスを含める | |
$scripter.Options.WithDependencies = $false #依存オブジェクトを含めない | |
$scripter.Options.DriAll = $true #参照整合性の出力を含める | |
$scripter.Options.ToFileOnly = $true #コンソール出力しない | |
$scripter.Options.Triggers = $true #トリガーを含める | |
$scripter.Options.AnsiPadding = $true # | |
$scripter.Options.AppendToFile = $true #ファイルに追記する | |
[Microsoft.SqlServer.Management.Smo.SqlSmoObject[]]$db.Tables | | |
%{ | |
#データベース選択のコマンドを出力 | |
Add-Content -Path $scriptFile -encoding Unicode -Value "USE [$databaseName]" | |
Add-Content -Path $scriptFile -encoding Unicode -Value "GO" | |
$datetime = (Get-Date).ToString("MM/dd/yyyy hh:mm:ss.fff") | |
$schema = $_.Schema | |
$tableName = $_.Name | |
$scripter.Options.FileName = "$scriptDir\$tableName.sql" #出力先ファイル | |
#Drop文を出力 | |
Add-Content -Path $scriptFile -encoding Unicode -Value "/****** Object: Table [$schema].[$tableName] Script Date: $datetime ******/" | |
$scripter.Options.ScriptDrops = $true | |
$scripter.Script($_) | |
#Create文を出力 | |
Add-Content -Path $scriptFile -encoding Unicode -Value "/****** Object: Table [$schema].[$tableName] Script Date: $datetime ******/" | |
$scripter.Options.ScriptDrops = $false | |
$scripter.Script($_) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment