尝试使用 SMO 传输对象将数据库从一个实例传输到另一个实例

Gan*_*989 1 sql-server powershell sql-server-2012 smo amazon-rds

架构表归 dbo 和另一个架构名称所有。下面的代码没有在任何表格上移动。我还需要添加其他东西才能传输表格吗?没有需要移动的存储过程或视图。

$xfr1 = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Transfer($prodServerDB.Databases[$devDatabase])

#Set this objects properties
$xfr1.DestinationLoginSecure           = $false
$xfr1.DestinationServer                = $devServer
$xfr1.DestinationLogin                 = $devUsername
$xfr1.DestinationPassword              = $devPassword
$xfr1.DestinationDatabase              = $devDatabase
$xfr1.BatchSize                        = 10485760
$xfr1.CopyData                         = $true
$xfr1.CopyAllTables                    = $true
$xfr1.CopyAllObjects                   = $true
$xfr1.CopyAllDatabaseTriggers          = $true
$xfr1.CopyAllLogins                    = $false
$xfr1.CopyAllRoles                     = $false
$xfr1.CopyAllUsers                     = $false
$xfr1.CopySchema                       = $true
$xfr1.PreserveDbo                      = $true
$xfr1.PreserveLogins                   = $true

$xfr1.Options.AllowSystemObjects       = $false
$xfr1.Options.ContinueScriptingOnError = $true
$xfr1.Options.Indexes                  = $true
$xfr1.Options.IncludeIfNotExists       = $true
$xfr1.Options.DriAll                   = $true
$xfr1.Options.SchemaQualify            = $true
$xfr1.Options.ScriptSchema             = $true
$xfr1.Options.ScriptData               = $true
$xfr1.Options.WithDependencies         = $true

# Script the transfer. Alternatively perform immediate data transfer with TransferData method.
# $xfr1.ScriptTransfer()
# $xfr1.EnumScriptTransfer()
$xfr1.TransferData()
Run Code Online (Sandbox Code Playgroud)

当前错误堆栈如下:

PS C:\powershell_sample_scripts> $Error | select *


ErrorRecord                 : Exception calling "TransferData" with "0" argument(s): "An error occurred while transferring data. See the inner exception for details."
StackTrace                  :    at System.Management.Automation.ExceptionHandlingOps.ConvertToMethodInvocationException(Exception exception, Type typeToThrow, String methodName, Int32 numArgs,
                              MemberInfo memberInfo)
                                 at CallSite.Target(Closure , CallSite , Object )
                                 at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
                                 at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
WasThrownFromThrowStatement : False
Message                     : Exception calling "TransferData" with "0" argument(s): "An error occurred while transferring data. See the inner exception for details."
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              : Microsoft.SqlServer.Management.Common.TransferException: An error occurred while transferring data. See the inner exception for details. --->
                              System.Data.SqlClient.SqlException: User, group, or role 'user_account' already exists in the current database.
                                 at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                                 at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                                 at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler,
                              TdsParserStateObject stateObj, Boolean& dataReady)
                                 at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
                                 at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean
                              asyncWrite)
                                 at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                                 at Microsoft.SqlServer.Management.Smo.Transfer.ExecuteStatements(SqlConnection destinationConnection, IEnumerable`1 statements, SqlTransaction transaction)
                                 at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
                                 --- End of inner exception stack trace ---
                                 at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
                                 at CallSite.Target(Closure , CallSite , Object )
TargetSite                  : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject] Invoke(System.Collections.IEnumerable)
HelpLink                    :
Source                      : System.Management.Automation
HResult                     : -2146233087

PSMessageDetails      :
Exception             : System.Management.Automation.MethodInvocationException: Exception calling "TransferData" with "0" argument(s): "An error occurred while transferring data. See the inner
                        exception for details." ---> Microsoft.SqlServer.Management.Common.TransferException: An error occurred while transferring data. See the inner exception for details. --->
                        System.Data.SqlClient.SqlException: User, group, or role 'user_account' already exists in the current database.
                           at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                           at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                           at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler,
                        TdsParserStateObject stateObj, Boolean& dataReady)
                           at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
                           at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
                           at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                           at Microsoft.SqlServer.Management.Smo.Transfer.ExecuteStatements(SqlConnection destinationConnection, IEnumerable`1 statements, SqlTransaction transaction)
                           at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
                           --- End of inner exception stack trace ---
                           at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
                           at CallSite.Target(Closure , CallSite , Object )
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
                           at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline tempPipeline, Exception& exceptionThrown, ExecutionOptions options)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : TransferException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, C:\powershell_sample_scripts\runMigration.ps1: line 150
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
Run Code Online (Sandbox Code Playgroud)

小智 5

由于我不确切知道您遇到了什么错误,我将根据您的代码和我选择测试的数据库让您知道我得到了什么错误。

我会注意到您正在使用的大部分属性在 SQL Server 2012 SMO 中无效(至少在我的机器上)

我用于脚本的最终结果在最后。在我的情况下,我遇到了一些不同的错误:

使用“0”参数调用“TransferData”的异常:“传输数据时出错。有关详细信息,请参阅内部异常。” 在行:46 字符:1

如果您收到此错误,您可以检查该Exception属性$error并找出原因: 在此处输入图片说明

我收到上述错误,因为我已经运行了一次并且它部分创建了对象。

我遇到的唯一其他错误与我必须检查Exception属性的性质相似,但其他错误与我选择测试的数据库过程中的代码有关。我更改为我拥有的数据库,它只有两个包含几百行数据的表,并且它没有错误地完成。

所以最后如果你想编辑你的问题以提供你可能得到的确切错误,如果我能弄清楚任何事情,我可以调整答案。

$error.Clear()

Add-Type -AssemblyName 'Microsoft.SqlServer.Smo,Version=11.0.0.0,Culture=neutral,publickeytoken=89845dcd8080cc91'
Add-Type -AssemblyName 'Microsoft.SqlServer.SmoExtended,Version=11.0.0.0,Culture=neutral,publickeytoken=89845dcd8080cc91'


$srv = New-Object Microsoft.SqlServer.Management.Smo.Server 'MANATARMS\SQL12'
$db = $srv.Databases["Credit"]
$dbDest = 'CreditCopy'

<# Main error I received was using this line as you had it formated: "Cannot index into a null array." #>
#$xfr1 = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Transfer($prodServerDB.Databases["Credit"])

$xfr1 = New-Object Microsoft.SqlServer.Management.Smo.Transfer($db)

#Set this objects properties
$xfr1.DestinationLoginSecure           = $true
$xfr1.DestinationServer                = 'MANATARMS\SQL12'
$xfr1.DestinationDatabase              = $dbDest
$xfr1.BatchSize                        = 10485760
$xfr1.CopyData                         = $true
$xfr1.CopyAllTables                    = $true
$xfr1.CopyAllObjects                   = $true
$xfr1.CopyAllDatabaseTriggers          = $true
$xfr1.CopyAllLogins                    = $false
$xfr1.CopyAllRoles                     = $false
$xfr1.CopyAllUsers                     = $false
$xfr1.CopySchema                       = $true
$xfr1.PreserveDbo                      = $true
$xfr1.PreserveLogins                   = $true

<# these properties does not exist on the object for 2012 SMO #>
##$xfr1.Options.AllowSystemObjects       = $false
##$xfr1.Options.ContinueScriptingOnError = $true
##$xfr1.Options.Indexes                  = $true
##$xfr1.Options.IncludeIfNotExists       = $true
##$xfr1.Options.DriAll                   = $true
##$xfr1.Options.SchemaQualify            = $true
##$xfr1.Options.ScriptSchema             = $true
##$xfr1.Options.ScriptData               = $true
##$xfr1.Options.WithDependencies         = $true

# Script the transfer. Alternatively perform immediate data transfer with TransferData method.
# $xfr1.ScriptTransfer()
# $xfr1.EnumScriptTransfer()
$xfr1.TransferData()
Run Code Online (Sandbox Code Playgroud)