Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

vbscript - Execute stored procedure and return resultset

I'm a complete VBScript newbie and I am trying to execute a stored procedure and read the resultset. I have tried numerous different approaches using articles online but nothing works and I'm stumped. The database is SQL Server 2008 R2, the application is an off-the-shelf ERP system but I'm able to add my own code to it.

I can execute code by using:

connection.execute"insert into blah blah blah"

And I can read result set by using:

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

The stored procedure in question is in effect a select statement e.g.:

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

My code so far:

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

But I cannot for the life of me get a procedure to execute and read the results.

Can anyone help?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

adCmdText would be for SQL query if you want to execute a stored procedure then you have to use adCmdStoredProc (value 4 instead)

EDIT:

'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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...