我们正在编写一个新的应用程序,在进行测试时,我们将需要一堆虚拟数据。我已经通过使用MS Access将excel文件转储到相关表中添加了这些数据。
每隔一段时间,我们想要“刷新”相关的表,这意味着将它们全部删除,重新创建它们,并运行已保存的MS Access追加查询。
第一部分(删除和重新创建)是一个简单的sql脚本,但最后一部分让我畏缩。我想要一个单独的设置脚本,它有一堆insert来重新生成虚拟数据。
我现在有数据在表格里。从该数据集自动生成一个大的INSERT语句列表的最佳方法是什么?
我能想到的唯一方法是将表保存到excel表格中,然后编写excel公式为每一行创建一个INSERT,这肯定不是最好的方法。
我使用2008 Management Studio连接到SQL Server 2005数据库。
我对这个问题的贡献是一个Powershell INSERT脚本生成器,它允许您为多个表编写脚本,而不必使用麻烦的SSMS GUI。非常适合快速将“种子”数据持久化到源代码控制中。
将下面的脚本保存为“filename.ps1”。
对“自定义我”下的区域进行自己的修改。
您可以以任意顺序将表列表添加到脚本中。
您可以在Powershell ISE中打开脚本并点击播放按钮,或者简单地在Powershell命令提示符中执行脚本。
默认情况下,生成的INSERT脚本将是“SeedData”。与脚本相同的文件夹下。
您需要安装SQL Server管理对象程序集,如果您安装了SSMS,则应该安装该程序集。
Add-Type -AssemblyName ("Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
Add-Type -AssemblyName ("Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
#CUSTOMIZE ME
$outputFile = ".\SeedData.sql"
$connectionString = "Data Source=.;Initial Catalog=mydb;Integrated Security=True;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = $srv.Databases[$srv.ConnectionContext.DatabaseName]
$scr = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scr.Options.FileName = $outputFile
$scr.Options.AppendToFile = $false
$scr.Options.ScriptSchema = $false
$scr.Options.ScriptData = $true
$scr.Options.NoCommandTerminator = $true
$tables = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
#CUSTOMIZE ME
$tables.Add($db.Tables["Category"].Urn)
$tables.Add($db.Tables["Product"].Urn)
$tables.Add($db.Tables["Vendor"].Urn)
[void]$scr.EnumScript($tables)
$sqlConnection.Close()
这也可以使用Visual Studio完成(至少在2013年版本开始)。
在VS 2013中,也可以过滤insert语句所基于的行列表,据我所知,这在SSMS中是不可能的。
请执行以下步骤:
Open the "SQL Server Object Explorer" window (menu: /View/SQL Server Object Explorer)
Open / expand the database and its tables
Right click on the table and choose "View data" from context menu
This will display the data in the main area
Optional step: Click on the filter icon "Sort and filter data set" (the fourth icon from the left on the row above the result) and apply some filter to one or more columns
Click on the "Script" or "Script to File" icons (the icons on the right of the top row, they look like little sheets of paper)
这将为活动窗口或文件的所选表创建(有条件的)插入语句。
Visual Studio 2013:滤镜和脚本