【问题标题】:Stored procedure called from Powershell does not execute via SMO object从 Powershell 调用的存储过程不通过 SMO 对象执行
【发布时间】:2016-12-17 20:19:28
【问题描述】:

我正在尝试使用以下代码从 Powershell 终端执行存储过程,但该过程似乎没有执行,并且终端中没有引发错误。

add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$so = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -argumentList 'PC-1001'
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($so, "TestDB")
$sproc = $db.StoredProcedures.Item("dproc")
$sproc.Execute

支持的SQL代码为:

create table dummytable (id int identity(1,1), ranwhen datetime default getdate(), dummyval varchar(10));

create procedure dproc as
begin
set nocount on
    insert into dummytable (dummyval)
    select char(datepart(hour, getdate()) * datepart(minute, getdate()) * datepart(second, getdate()) % 256)
end

如果我在 SSMS (exec dproc) 中执行该过程,它可以工作(数据被插入到表中)。

任何想法为什么它不能在 Powershell 中工作? (没有数据被插入到虚拟表中)

更新:

我已将$db$sproc 变量的声明更改为:

$db = $so.Databases.Item("TestDB")
$sproc = $db.StoredProcedures.Item("dproc")

当检查$sproc 对象的内容时,我可以看到每个属性都是正确的(T-SQL 代码在那里,URN 值正确并且引用了正确的数据库和架构)。

【问题讨论】:

  • 尝试给execute方法加上大括号,比如$sproc.Execute()
  • 您是否尝试过同时指定架构?就像 $sproc = $db.StoredProcedures.Item("dproc", "dbo") -- 或者它是什么模式
  • @KirillPashkov 抛出错误:“方法调用失败,因为 [Microsoft.SqlServer.Management.Smo.StoredProcedure] 不包含名为 'Execute' 的方法。”
  • 当您运行它时,您在控制台中根本看不到任何返回,对吧? $sproc.Execute。如果这是一种方法,您将需要$proc.Execute()。问题是,该课程的任何文档都没有表明您的尝试是可能的。
  • @RaduGheorghiu 我正在使用 System.Data.SqlClient 与 db 交互,ExecuteNonQuery 在那里工作,这就是为什么我搜索 MSDN 并发现该方法可以通过 SMO 使用 (link) ,这就是为什么我建议你尝试一下。

标签: sql-server powershell stored-procedures


【解决方案1】:

StoredProcedure 类不提供执行它所代表的存储过程的方法。

您可以尝试,我没有采取任何步骤来验证这是可能的,使用:

$so.ConnectionContext.ExecuteNonQuery("dproc")

如果做不到这一点,您可能会简单地回退到使用 System.Data.SqlClient。

【讨论】:

  • $so.ConnectionContext.ExecuteNonQuery("dproc") 不起作用,但我会调查Data.SqlClient
【解决方案2】:

我建议您也使用 System.Data.SqlClient。我曾经运行过这样的存储过程:

$SQL = New-Object System.Data.SqlClient.SqlConnection
$ConnectionStrig = "Server=localhost;Database=testtaskdb;Integrated Security=True;"
$SQL.ConnectionString = $ConnectionStrig
$SQL.Open()
$CMD = $SQL.CreateCommand()
$CMD.CommandText = "exec myproc"

#if you need to just run the stored procedure
$null=$CMD.ExecuteReader()

#if you need to get the output
$Table = New-Object System.Data.DataTable
$Table.Load($CMD.ExecuteReader())
Write-Output $Table

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2011-12-14
    • 2015-05-08
    • 2019-05-07
    • 1970-01-01
    • 2020-03-31
    相关资源
    最近更新 更多