Skip to content

Instantly share code, notes, and snippets.

@nakaji
Created September 14, 2012 14:22
Show Gist options
  • Save nakaji/3722200 to your computer and use it in GitHub Desktop.
Save nakaji/3722200 to your computer and use it in GitHub Desktop.
データベース内の全テーブルをCreateするスクリプト
#参考:http://technet.microsoft.com/ja-jp/sqlserver/ff730155.aspx
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$serverName = "localhost\SQLEXPRESS"
$databaseName = "AdventureWorks"
$scriptFile = "D:\テーブル.sql"
#追記するので既にファイルがある場合は出力ファイルを削除する
if (Test-Path $scriptFile) {
Remove-Item $scriptFile
}
#データベース選択のコマンドを出力
Add-Content -Path $scriptFile -encoding Unicode -Value "USE [$databaseName]"
Add-Content -Path $scriptFile -encoding Unicode -Value "GO"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($serverName)
$db = $server.Databases[$databaseName]
$scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter($server)
#出力するスクリプトの設定
$scripter.Options.FileName = $scriptFile #出力先ファイル
$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 |
%{
$datetime = (Get-Date).ToString("MM/dd/yyyy hh:mm:ss.fff")
$schema = $_.Schema
$tableName = $_.Name
#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