我正在尝试使用以下代码从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值是正确的,并且引用了正确的数据库和模式)。
答案 0 :(得分:3)
StoredProcedure类不提供执行它所代表的存储过程的方法。
您可以尝试,我没有采取任何措施来验证这是可能的,使用:
$so.ConnectionContext.ExecuteNonQuery("dproc")
如果做错了,你可能会回到使用System.Data.SqlClient。
答案 1 :(得分:1)
我建议您也使用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