Here我找到了手动创建数据播种脚本的解决方案。手动解决方案允许我选择要生成插入的表
我想知道是否可以选择通过 PowerShell 运行相同的进程?
到目前为止,我已经管理了如何创建一个 SQL 脚本来创建数据库 架构 播种机:
[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
}
但是有没有类似的方法来生成 数据播种脚本?
有任何想法吗?干杯
最佳答案
您可以使用 SMO scripter class .这将允许您编写表创建的脚本以及 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.
}
关于sql - 使用 PowerShell 和 SSMS 生成数据播种脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629308/