你可以使用
SMO scripter class
. 这将允许您编写表创建的脚本以及
INSERT
表中数据的语句。
在我的示例中,我直接针对tempdb并定义一个表名数组,我希望编写脚本而不是编写每个表的脚本。
脚本编写器有很多可用的选项,所以在这个例子中我只做了一小部分-这个任务的重要选项是
Options.ScriptData
. 如果没有它,你只会得到你已经得到的模式脚本。
最后的EnumScript方法完成了生成脚本、输出脚本以及将脚本附加到选项中指定的文件的实际工作。
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
## target file
$outfile = 'f:\scriptOutput.sql'
## target server
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "localhost"
## target database
$db = $s.databases['tempdb']
## array of tables that we want to check
$tables = @('Client','mytable','tablesHolding')
## new Scripter object
$tableScripter = new-object ('Microsoft.SqlServer.Management.Smo.Scripter')($s)
##define options for the scripter
$tableScripter.Options.AppendToFile = $True
$tableScripter.Options.AllowSystemObjects = $False
$tableScripter.Options.ClusteredIndexes = $True
$tableScripter.Options.Indexes = $True
$tableScripter.Options.ScriptData = $True
$tableScripter.Options.ToFileOnly = $True
$tableScripter.Options.filename = $outfile
## build out the script for each table we defined earlier
foreach ($table in $tables)
{
$tableScripter.enumscript(@($db.tables[$table])) #enumscript expects an array. this is ugly, but it gives it what it wants.
}