代码之家  ›  专栏  ›  技术社区  ›  GoldenAge

使用PowerShell和SSMS生成数据种子设定脚本

  •  4
  • GoldenAge  · 技术社区  · 6 年前

    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
    } 
    

    但是,是否有类似的方法生成 数据 播种脚本?

    有什么想法吗?干杯

    1 回复  |  直到 6 年前
        1
  •  1
  •   GreyOrGray    6 年前

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