【问题标题】:Generate data seeding script using PowerShell and SSMS使用 PowerShell 和 SSMS 生成数据播种脚本
【发布时间】:2019-02-11 11:12:49
【问题描述】:

Here我找到了手动创建数据种子脚本的解决方案。手动解决方案允许我选择要为哪些表生成 inserts

我想知道是否有通过 PowerShell 运行相同进程的选项?

到目前为止,我已经管理了如何创建用于创建数据库 schema 播种器的 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
} 

但是有没有类似的方法来生成数据种子脚本?

有什么想法吗?干杯

【问题讨论】:

  • 问题到底是什么?如果您可以将其更改为作为纯 powershell 运行?
  • 我想使用 PowerShell 从 SSMS 运行数据播种功能并生成 SQL 脚本
  • LoadWithPartialName 现在是 obsolete。 PowerShell V3 及更高版本的推荐解决方案是使用 Add-Type cmdlet。
  • 好的,我会记住这一点,但是是否有一个选项可以构建类似的脚本来为每个表创建种子脚本?

标签: sql powershell tsql ssms


【解决方案1】:

您可以使用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.
} 

【讨论】:

  • 我只想生成数据种子脚本。它还生成模式播种器脚本。如何禁用第二件事?
  • 好的,我在文档中找到了。需要加$tableScripter.Options.ScriptSchema = $False
  • 您的解决方案似乎有效。我read 说 SMO 是一个 NuGet 包。我只是想知道这个脚本需要在机器上安装 SSMS 还是只需要 .net framework 4.0> 才能运行它?
  • 您不需要安装 SSMS 即可工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 2019-06-04
相关资源
最近更新 更多