与DbaTools相关的-https://dbatools.io/functions/
你好,
我正在尝试寻找一种解决方案来复制表并在-Destination / -DestinationDatabase
上创建它。
我正在使用:
Get-DbaTable -SqlInstance "Machine1" -Database DBA -Table "Table01" | Copy-DbaTableData -Destination "Machine2\PANDA" -DestinationDatabase PANDA01 -DestinationTable "Table01"
但是由于表不是在目标上创建的,因此出现错误消息:
警告:[15:25:58] [Copy-DbaTableData] Table01不存在于 目的地
请问有什么方法可以在DestinationDatabase上复制和创建表?
答案 0 :(得分:1)
这是我用于类似任务的内容-
# Configuration for scripting options: Which related objects should also be scripted?
$so = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions;
$so.DriAllConstraints = $true;
$so.DriAllKeys = $true;
$so.DriClustered = $true;
$so.DriDefaults = $true;
$so.DriIndexes = $true;
$so.DriNonClustered = $true;
$so.DriPrimaryKey = $true;
$so.DriUniqueKeys = $true;
$so.AnsiFile = $true;
$so.ClusteredIndexes = $true;
$so.IncludeHeaders = $true;
$so.Indexes = $true;
$so.SchemaQualify = $true;
$so.Triggers = $true;
$so.XmlIndexes = $true;
#Hard-Coding the Server and database info
$SourceServer = "SourceServer"
$SourceDatabase = "SourceDatabase"
$TargetServer = "TargetServer"
$TargetDatabase = "TargetDatabase"
#Creating folders for storing Create_Database text files if they don't exist
If(!(Test-Path E:\ScriptDatabases))
{
New-Item -ItemType Directory -Force -Path E:\ScriptDatabases
}
#Creating the database connection object for Source server
$Srcsrv = new-Object Microsoft.SqlServer.Management.Smo.Server($Sourceserver);
$Srcdb = New-Object Microsoft.SqlServer.Management.Smo.Database;
$Srcdb = $Srcsrv.Databases.Item($SourceDatabase);
#Creating the database connection object for Destination server
$Destsrv = new-Object Microsoft.SqlServer.Management.Smo.Server($TargetServer);
$Destdb = New-Object Microsoft.SqlServer.Management.Smo.Database;
$Destdb = $Destsrv.Databases.Item($TargetDatabase);
foreach ($table in $Srcdb.Tables)
{
$table.Script($so) | Out-File -FilePath E:\ScriptDatabases\$($table.Name).txt
$CreatedbQuery = Get-Content E:\ScriptDatabases\$($table.Name).txt | Out-String
Invoke-sqlcmd -Query $CreatedbQuery -Database $TargetDatabase -server $TargetServer
}
上面的脚本将从源数据库到文本文件的所有表脚本化,然后从文本文件中读取它们,并在目标数据库和目标服务器上创建表。没什么要记住的-
dbo
以外还有其他任何模式,则需要首先创建这些模式。否则,将不会为其他模式创建您的表。$true
或$false
。您可以在创建表之后运行Get-DbaTable -SqlInstance "Machine1" -Database DBA -Table "Table01" | Copy-DbaTableData -Destination "Machine2\PANDA" -DestinationDatabase PANDA01 -DestinationTable "Table01"
,也可以在创建表本身之后在脚本中循环执行,以便同时进行表创建和向表中加载数据。这完全是您的选择,我将自行决定。希望这会有所帮助!