使用RedGate sqlcompare&创建架构克隆服务器名称表

时间:2014-04-16 20:38:04

标签: sql-server tsql redgate

好的,所以我采用了以前DBA已经习惯的旧批处理文件" clone"来自多个服务器上的生产数据库的模式,并将它们放在一个网络目录中。此批处理文件已手动更新,因此我尝试将其自动化。我们有一个支持dbase,其中包含一个包含所有服务器名称的表,所以我想通过执行&#34的服务器名称列表,最简单的是光标(我知道,但这不是问题) ; sqlcompare"每个命令行的东西。显然,虽然它为每个服务器上的每个单独的数据库创建了一个新的命令行,所以我的变量返回了多个结果。有一个更好的方法来做到这一点,我觉得我必须做到这一切都错了,任何帮助表示赞赏:

  DECLARE @RowCount INT = 1
 ,@index INT = 1
 ,@outputfolder varchar(100)
 ,@servername varchar(100)
 ,@environment varchar(50)
 ,@OutputPath  varchar(100)
 ,@sqlcmd nvarchar (100)

SET @outputfolder = GETDATE()
SET @OutputPath = '\\<network location to store output files>\'

-- set @outputfolder = '2014.03.10_0900'
SET @servername = '<servername stored in table>'
SET @environment = '<environment variable in table>'
SET @sqlcmd = ':connect '+@servername

DECLARE @redgatecmd varchar(255)
SET @redgatecmd = ''

--SELECT '::'+@environment
SET @redgatecmd = (SELECT DISTINCT 'sqlcompare /s1:'+@servername+' /db1:'+'name'+' /mkscr:"'+@OutputPath+@outputfolder+'\'+@environment+'\'+'name'+'" /options:iw,iu,isn,ie,ic,iup,iweo,infr,idc,idsn,isoa,isb"' from sysdatabases where name not in ( 'tempdb'))
PRINT @redgatecmd

--EXEC master..xp_cmdshell @redgatecmd

1 个答案:

答案 0 :(得分:3)

我使用PowerShell做了类似的事情。并从那里连接到数据库以提取细节。为你的例子调整它(虽然输出目录不是完全相同,并且它没有设置比较选项)

它基于此great article from DataOrge

#Create your SQL connection string, and then a connection
$ServerAConnectionString = "Data Source=hostname\instance;Initial Catalog=databasename;Integrated Security=SSPI" # Or instead of integrated auth ;User Id=XXX;PWD=XXX"
$ServerAConnection = new-object system.data.SqlClient.SqlConnection($ServerAConnectionString);

#Create a Dataset to hold the DataTable 
$dataSet = new-object "System.Data.DataSet" "ServerList"
$query = "SET NOCOUNT ON;"
$query = $query + "SELECT name, environment, db "
$query = $query + "FROM   dbo.Servers; "


#Create a DataAdapter which you'll use to populate the DataSet with the results
$dataAdapter = new-object "System.Data.SqlClient.SqlDataAdapter" ($query, $ServerAConnection)
$dataAdapter.Fill($dataSet) | Out-Null

#Close the connection as soon as you are done with it
$ServerAConnection.Close()


$dataTable = new-object "System.Data.DataTable" "Servers"
$dataTable = $dataSet.Tables[0]


#For every object
$dataTable | FOREACH-OBJECT {
  "Name:  $($_.name)"
  "Database:  $($_.db)"
  "Environment:  $($_.environment)"

  $cmd = "sqlcompare.exe /s1:$($_.name) /db1:$($_.db) /mkscr:$($_.environment+"_"+$_.db)"
  write-host $cmd
  Invoke-Expression $cmd
}