Sql 使用PowerShell和SSMS生成数据种子脚本
我找到了手动创建数据种子脚本的解决方案。手动解决方案允许我选择要为哪些表生成插入 我想知道是否有通过PowerShell运行相同进程的选项 到目前为止,我已经设法创建了一个SQL脚本,该脚本创建了数据库模式种子机:Sql 使用PowerShell和SSMS生成数据种子脚本,sql,powershell,tsql,ssms,Sql,Powershell,Tsql,Ssms,我找到了手动创建数据种子脚本的解决方案。手动解决方案允许我选择要为哪些表生成插入 我想知道是否有通过PowerShell运行相同进程的选项 到目前为止,我已经设法创建了一个SQL脚本,该脚本创建了数据库模式种子机: [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null $s = new-object ('Microsoft.SqlServer.Management.Smo
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "(localdb)\mssqlLocalDb"
$dbs=$s.Databases
#$dbs["HdaRoot"].Script()
$dbs["HdaRoot"].Script() | Out-File C:\sql-seeding\HdaRoot.sql
#Generate script for all tables
foreach ($tables in $dbs["HdaRoot"].Tables)
{
$tables.Script() + "`r GO `r " | out-File C:\sql-seeding\HdaRoot.sql -Append
}
但是,是否有类似的方法来生成数据种子脚本
有什么想法吗?干杯您可以使用。这将允许您为表中的数据创建脚本以及INSERT
语句
在我的示例中,我直接以TempDB为目标,并定义了一个表名数组,我想编写脚本,而不是编写每个表的脚本
Scripter有很多可用的选项,所以在本例中我只做了很少的一部分-此任务的重要选项是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.
}
问题到底是什么?如果可以将其更改为作为纯powershell运行?我想使用powershell从SSMS运行数据种子设定功能,并立即生成SQL scriptLoadWithPartialName。PowerShell V3及更高版本的建议解决方案是使用Add-Type cmdlet。好的,我会记住这一点,但是是否有一个选项可用于为每个表创建种子脚本来构建类似的脚本?我只想生成数据种子脚本。它还生成模式播种器脚本。如何禁用第二件事?好的,我在文档中找到了。需要添加
$tableScripter.Options.ScriptSchema=$False
您的解决方案似乎有效。我听说SMO是一个NuGet软件包。我只是想知道这个脚本需要在机器上安装SSMS,还是只需要.net framework 4.0>就可以运行?您不需要安装SSMS就可以运行它。