How to run a stored procedure with param and store result as a record set in classic asp - asp-classic

I wasn't able to find a question/answer that covers this fully hence why I am asking. What I need to do is run a stored procedure that takes 1 parameter. It will return a set of results which I need to store in a record set. I plan to loop through this recordset later. I'm pretty inexperienced when it comes to older asp, but here is what I have to far:
dim myConn
Set myConn = Server.CreateObject("ADODB.Connection")
myConn.Open = ("DSN=example-dsn;SERVER=example-server;DATABASE=example-db;UID=user;PWD=pass;")
dim oStoredProc : Set oStoredProc = Server.CreateObject("ADODB.Command")
With oStoredProc
.ActiveConnection = myConn
.CommandType = adCmdStoredProc
.CommandText = "myStoredProcedure"
.Parameters.Append(.CreateParameter("#PARAM1", ADODB.adInteger, ADODB.adParamInput, 10, 2012))
Dim rs : Set rs = .Execute()
End With
// Will loop through it here.
My guess is that I'm not setting up the recordset right, but like I said, I'm not really sure. If anyone can point me in the right direction I'd appreciate it!

You will want to make sure your result set is the correct object
set rs = Server.CreateObject("ADODB.Recordset")
Then you will use the open method I think it works something like this:
rs.Open oStoredProc
Then use the other members of the Record Set object to loop through the results.

Alright there were a few things I was doing wrong but here is what ended up working for me. First off it turns out I didn't need a parameter passed in, but that was not the problem anyway. One of the main issues what that 'adCmdStoredProc' wasn't recognized, which is odd because I've seen it used everywhere else, but replacing it with it's corresponding value, 4, did work.
dim myConn, cmd
Set myConn = Server.CreateObject("ADODB.Connection")
myConn.Open = ("DSN=[BLAH];SERVER=[SERVER];DATABASE=[BLAH];UID=[User];PWD=[Pass];")
dim oStoredProc : Set oStoredProc = Server.CreateObject("ADODB.Command")
oStoredProc.CommandType = 4
oStoredProc.CommandText = "StoredProcedureName"
oStoredProc.ActiveConnection = myConn
// Add parameters here if needed.
Dim rs
Set rs = oStoredProc.Execute()
// I Loop through here
rs.Close
myConn.Close
Set rs = Nothing
Set oStoredProc = Nothing
Set myConn = Nothing
I hope this helps if anyone else needs it.

Dim rsStk As New ADODB.Recordset
Set rsStk = cnnPck.Execute("SP_JOB_ALL '" & Trim(te_Item) & "'")
Set Recordset= CONNECTION .Execute()
This one is simple way to do this thing

Related

How to get the total number of records count from a sql ado dB connection in classic asp [duplicate]

I am newbie in VBScript and I've come across with the following problem. I want get data from sql server db and to allow RecordCount properties. Next code get data but RecordCount is disabled. How can I enable this properties
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=BUG\SQLSERVER2005;Initial Catalog=test;user id ='sa';password='111111'"
Set myConn = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command" )
myConn.Open DB_CONNECT_STRING
Set myCommand.ActiveConnection = myConn
myCommand.CommandText = ("select * from klienci k where k.indeks = " & oferty(16))
Set klienci = myCommand.Execute
AFAIK you can't change the cursor type when using the Execute method of the Command object, and you can't change the cursor type after you retrieved the recordset. Something like this might work, though:
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=BUG\SQLSERVER2005;Initial Catalog=test;user id ='sa';password='111111'"
Set myConn = CreateObject("ADODB.Connection")
myConn.Open DB_CONNECT_STRING
query = "select * from klienci k where k.indeks = " & oferty(16)
Set klienci = CreateObject("ADODB.Recordset")
klienci.CursorLocation = 3 'adUseClient
klienci.CursorType = 3 'adOpenStatic
klienci.LockType = 1 'adLockReadOnly
klienci.Open query, myConn
I don't think this is a VBScript issue- I think it is an ADO issue.
I think you are using a default forward-only cursor which won't work with recordcount.
I think you should stick a cursortype=adOpenStatic in there but I'm having a little trouble determining if you are specifying a recordset object - klienci?
If so try
klienci.cursortype=adOpenStatic

SQLClient output parameter returns DBNull

Its a ASP.net application in VS2008, connecting to SQL 2005 database.
No errors calling the Stored procedure, db update is successful but the OUTPUT param returns DBnull all the time. Below the vb code:
Dim ConnectString As String = "", connect As New Data.SqlClient.SqlConnection
ConnectString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connect.ConnectionString = ConnectString
Dim cmd As New SqlCommand("saveAccess", connect)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("#Name", "SampleName"))
Dim outparam As SqlParameter = New SqlParameter("#returnValue", SqlDbType.Int)
outparam.Direction = ParameterDirection.Output
cmd.Parameters.Add(outparam)
connect.Open()
cmd.ExecuteNonQuery()
If IsDBNull(cmd.Parameters("#returnValue").Value Then
Response.Write("Why does it always returns DBNull")
Else : Response.Write(cmd.Parameters("#returnValue").Value.ToString())
End If
connect.Close()
Here is the SQL code
ALTER PROCEDURE [dbo].[saveAccess]
(#Name NVARCHAR(20), #returnValue INT OUTPUT )
AS
BEGIN
INSERT INTO Access ([Name]) VALUES (#Name);
SELECT #returnValue = ##ROWCOUNT;
END
Not sure what is the silly mistake that I am doing. Any input helps.
Thanks
Instead of SELECT, try using SET to set the value of the output parameter
SET #returnValue = ##ROWCOUNT;
Solution (as said silly myself): missed the # symbol in front of the returnValue variable. I typed up the code in this posting correctly but I had it without the # in the SP.
wrong: SELECT returnValue = ##ROWCOUNT;
correct: SELECT #returnValue = ##ROWCOUNT;
Thanks

How can I use an ADODB.CommandObject with ADODB.RecordSet?

I am trying to make a Classic ASP/VBScript website more secure by making SQL statements parameterized.
I have the following function:
Function OpenUpdateableRS(strSQL)
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQL, cnDZ, adOpenKeyset, adLockPessimistic, adCmdText
Set OpenUpdateableRS = rs
Set rs = Nothing
End Function
I intend to convert it to something like:
Function SecureOpenUpdateableRS(strSQL, strParam1, strParam2)
Dim rs
Dim cmdOB
Set cmdOB = Server.CreateObject("ADODB.CommandObject")
With cmdOB
.ActiveConnection = cnDZ
.CommandText = strSQL
.Parameters(0).value = strParam1
.Parameters(0).value = strParam2
End With
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open cmdOB.Execute, , adOpenKeyset, adLockPessimistic
Set SecureOpenUpdateableRS = rs
Set rs = Nothing
End Function
When I call the function with:
Set rs = SecureOpenUpdateableRS("SELECT CustID, LastActive, LoggedIn, SessionID FROM tblLogins WHERE EMail = ? AND PWord = ?", strEMail, strPassword)
I get a "500 - Internal Server Error" which is probably because I disabled debugging on the server.
Any ideas on how I could make the original function more secure without breaking it?
You'll have to create the parameters and append them to the command's parameter collection. Just assigning the values to (the same!) parameter can't possibly work. Google for a sample; perhaps this VB! sample will get you started.
Added:
I can think of two strategies to derive the parameter types:
If you pass the correct/maximally specified parameter values to the function you can map VarType(value) constants to parameter type constants
If you do a SELECT based on the fieldnames in the command text, you can map the recordset's field .Types to parameter type constants
It won't be trivial to get this right for all possible cases. I would pass pairs of value and desired type to the function.

Syntax error (missing operator) in query expression

I know it is a common error, but I still can't solve it myself.
What I am trying to do is I have a SELECT item called status that allow the user to choose their employment status, I want to simply get the result and update the user_table(access file) status cell.
Any reply will be greatly appreciated!
The Code is below:
<!--#include file="../conn/conn.asp"-->
<%
id=request.QueryString("id")
status=request.Form("status")
sql="select * from user_table where id="&id
set rs=conn.execute(sql)
sql="update user_table set Status='"+status+"' where id="&id
'response.Write sql
conn.execute(sql)
conn.close
response.Write "<script>alert('Change Sucessful!');</script>"
set conn=nothing
response.end()
%>
I think you may be having a problem with conn.execute(sql) as well as response.end()
To fix it, you need to do either:
conn.execute sql
or
Call conn.execute(sql)
But, yeah, you should follow other comments posted as your technique has security issues. You should consider changing it to use parameters:
<!--#include file="../conn/conn.asp"-->
<%
id = request.QueryString("id")
status = request.Form("status")
sql = "select * from user_table where id = #id"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = sql
Set cmd.ActiveConnection = conn
cmd.Prepared = True
cmd.Parameters.Refresh
cmd.Parameters("#id") = id
Set rs = cmd.Execute
Set rs = nothing
Set cmd = nothing
sql = "update user_table set status = #status where id = #id"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = sql
Set cmd.ActiveConnection = conn
cmd.Prepared = True
cmd.Parameters.Refresh
cmd.Parameters("#status") = status
cmd.Parameters("#id") = id
Set rs = cmd.Execute
Set rs = nothing
Set cmd = nothing
response.Write "<script>alert('Change Sucessful!');</script>"
Set conn = nothing
response.end
%>
I'm guessing conn.asp leaves conn open? otherwise you need to open it. Also, what shows when you uncomment the response.write sql line?
And, you are definitely opening yourself to hackers. You need to 'clean' anything that comes from a request.form or request.querystring (with at the very least, a replace(..., "'", "''"), or much better, use stored procedures instead of straight sql

ASP Classic Named Parameter in Paramaterized Query: Must declare the scalar variable

I'm trying to write a parameterized query in ASP Classic, and it's starting to feel like i'm beating my head against a wall. I'm getting the following error:
Must declare the scalar variable "#something".
I would swear that is what the hello line does, but maybe i'm missing something...
<% OPTION EXPLICIT %>
<!-- #include file="../common/adovbs.inc" -->
<%
Response.Buffer=false
dim conn,connectionString,cmd,sql,rs,parm
connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=.\sqlexpress;Initial Catalog=stuff"
set conn = server.CreateObject("adodb.connection")
conn.Open(connectionString)
set cmd = server.CreateObject("adodb.command")
set cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = "select #something"
cmd.NamedParameters = true
cmd.Prepared = true
set parm = cmd.CreateParameter("#something",advarchar,adParamInput,255,"Hello")
call cmd.Parameters.append(parm)
set rs = cmd.Execute
if not rs.eof then
Response.Write rs(0)
end if
%>
Here's some sample code from an MSDN Library article on preventing SQL injection attacks. I cannot find the original URL, but googling the title keywords (Preventing SQL Injections in ASP) should get you there quick enough. Hope this real-world example helps.
strCmd = "select title, description from books where author_name = ?"
Set objCommand.ActiveConnection = objConn
objCommand.CommandText = strCmd
objCommand.CommandType = adCmdText
Set param1 = objCommand.CreateParameter ("author", adWChar, adParamInput, 50)
param1.value = strAuthor
objCommand.Parameters.Append param1
Set objRS = objCommand.Execute()
See the following page on MSDN, near the bottom, referring specifically to named parameters.
MSDN example
ADO is going to expect question marks instead of actual parameter names in this case. Right now, the SQL "select #something" is not actually parameterized: it sees the "#something" as an (undeclared) SQL variable, not as a parameter. Change your CommandText line to this:
cmd.CommandText = "select ?"
And I think you will get the result you are looking for.
Good luck!
with server.createobject("adodb.command")
.activeConnection = application("connection_string")
.commandText = "update sometable set some_col=? where id=?"
.execute , array(some_value, the_id)
end with
I'm not sure what your query is intended to accomplish. I'm also not sure that parameters are allowed in the select list. MSDN used to have (many years ago, probably) a decent article on where parameters were allowed in a query, but I can't seem to find it now.
OTTOMH, your attempts to supply the parameter values to ADO look correct. Does your query execute if you do something like this?
SELECT 1 FROM sometable WHERE somefield = #something

Resources