【问题标题】:Powershell SQL Server stored procedure backupPowershell SQL Server 存储过程备份
【发布时间】:2020-07-09 06:07:18
【问题描述】:

我正在尝试通过从 Python 程序传递参数来备份 SQL Server 数据库中的一个特定存储过程。这是我尝试过的代码,但我不断收到错误。

param([string]$server='dbsed0898', [string]$dbname='global_hub',[string]$sp='dbo.gs_eligibility')

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out-null

$SMOserver = 'Microsoft.SqlServer.Management.Smo' #-argumentlist $server
$srv = New-Object("$SMOserver.Server") $server
$db = $srv.databases[$dbname]

$Objects = $db.storedprocedures[$sp]
$scripter = new-object ("$SMOserver.Scripter") $srv

$Scripter.Script($Objects) | Out-File 
" C:\Users\fthoma15\Documents\backup_03212020.sql"

$db = $SMOserver.databases[$dbname]

$Objects = $db.storedprocedures[$sp]
$Scripter.Script($Objects) | Out-File 

“C:\Users\fthoma15\Documents\backup_03212020.sql”

错误:

为“脚本”和参数计数找到多个模棱两可的重载:“1”。
在行:12 字符:5
+ $Scripter.Script($Objects) |输出文件“C:\Users\fthoma15\Document ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest

有人可以帮我吗?

【问题讨论】:

  • 我认为您还没有将$Scripter 声明为对象。所以你得到了例外。
  • 嗨! @WasifHasan,感谢您的回复。我已经改变了上面的代码,但现在我收到了一个新的错误,上面粘贴了。
  • 您可能错误地使用了StoredProcedureCollection,因此它返回了一个 $null 对象。您可以调用Item[String],其中字符串是没有模式的名称,或者调用Item[String, String],其中第一个字符串是名称,第二个字符串是模式。 (似乎倒退了,我知道。) REF: [StoredProcedureCollection.Item[String, String] Property](docs.microsoft.com/en-us/dotnet/api/…)
  • @AlwaysLearning 感谢您指引我正确的方向。在下面发布答案

标签: sql-server powershell stored-procedures backup


【解决方案1】:

这就是我所做的。

param([string]$server='test', [string]$dbname='test',[string[]]$sp=('test','test'))

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | out- 
null

$SMOserver = new-object ("Microsoft.SqlServer.Management.Smo.Scripter") #-argumentlist 
$server
$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("$server")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $srv.Databases.Item("$dbname")
$Objects = $db.storedprocedures[$sp[1,3]]
$scripter = new-object ("$SMOserver") $srv

$Scripter.Script($Objects) | Out-File 
"C:\Users\fthoma15\Documents\backup_03212020.sql"

按照 AlwaysLearning 的建议,我将 sp 变量更改为数组列表,拆分模式和 sp 名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多