Gol*_*Age 11 sql t-sql powershell ssms
在这里,我找到了手动创建数据种子脚本的解决方案.手动解决方案允许我选择要生成插入的表
我想知道是否有通过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
}
Run Code Online (Sandbox Code Playgroud)
但有没有类似的方法来生成数据种子脚本?
有任何想法吗?干杯
小智 5
您可以使用SMO 脚本编写器类。这将允许您编写表创建以及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.
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
360 次 |
最近记录: |