执行存储过程并返回结果集

时间:2013-10-31 12:13:48

标签: vbscript

我是一个完整的VBScript新手,我正在尝试执行存储过程并读取结果集。我尝试了许多不同的方法在线使用文章,但没有任何作用,我很难过。数据库是SQL Server 2008 R2,该应用程序是一个现成的ERP系统,但我可以添加自己的代码。

我可以使用:

执行代码
connection.execute"insert into blah blah blah"

我可以使用以下方法阅读结果集:

Set objRS = CreateObject("ADODB.Recordset")

objRS.Open "select a, b, c FROM blahblah", Connection, adOpenStatic, adLockBatchOptimistic,    adCmdText
If objRS.EOF = False Then
    a = objRS.Fields("a").Value
    b = objRS.Fields("b").Value
    c = objRS.Fields("c").Value
End If
objRS.Close

有问题的存储过程实际上是一个选择语句,例如:

create procedure [dbname].[dbo].[sptestproc] 
as 
    @Option1 Varchar(10) = NULL,
    @Option2 Varchar(10) = NULL
AS
BEGIN
    select first, second 
    from table1 
    where a = @option1 and b = @toption2
End

到目前为止我的代码:

Dim sql

sql = "EXEC [dbname].[dbo].[sptestproc] '" & Opt1 & "','" & Opt2 & "'"
Set RS = CreateObject("ADODB.Recordset")
RS.Open sql, Connection, adOpenStatic, adLockBatchOptimistic, adCmdText
Do While Not RS.EOF
    Call App.MessageBox("first",vbInformation,"Data updated")
    Call App.MessageBox("second",vbInformation,"Data updated")
    RS.MoveNext
Loop

但我不能为我的生活获得执行和阅读结果的程序。

有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:6)

adCmdText将用于SQL查询,如果要执行存储过程,则必须使用adCmdStoredProc(值4

编辑:

'Set the connection
'...............

'Set the command
DIM cmd
SET cmd = Server.CreateObject("ADODB.Command")
SET cmd.ActiveConnection = Connection

'Set the record set
DIM RS
SET RS = Server.CreateObject("ADODB.recordset")

'Prepare the stored procedure
cmd.CommandText = "[dbo].[sptestproc]"
cmd.CommandType = 4  'adCmdStoredProc

cmd.Parameters("@Option1 ") = Opt1 
cmd.Parameters("@Option2 ") = Opt2 

'Execute the stored procedure
SET RS = cmd.Execute
SET cmd = Nothing

'You can now access the record set
if (not RS.EOF) THEN
    first = RS("first")
    second = RS("second")
end if

'dispose your objects
RS.Close
SET RS = Nothing

Connection.Close
SET Connection = Nothing

答案 1 :(得分:0)

Connection.执行“SET NOCOUNT ON”

之前

SET cmd.ActiveConnection = 连接

我做得很好。

相关问题