How to call a stored procedure using asp classic? - sql

I am using sql server and asp classic, and am currently calling queries like this:
newHireSQL = "select * from NewHire where Archived = 0 order by HireID desc"
Set rsGetHireID = Server.CreateObject("ADODB.Recordset")
rsGetHireID.Open newHireSQL,ConnectionString,adOpenStatic
NumOfHireID = rsGetHireID.RecordCount
But instead of having the query statement here, I want to call a stored procedure called dbo.sp_selectNewHireSQL. How can I do that?
Thanks
EDIT:
I tried this
Dim Conn
SET Conn = Server.CreateObject("ADODB.Connection")
SET rsGetHireID = Server.CreateObject("ADODB.RecordSet")
Conn.Open ConnectionString
set rsGetHireID=Conn.Execute("Exec sp_selectNewHireSQL")
NumOfHireID = rsGetHireID.RecordCount
Response.Write (NumOfHireID)
But I am getting a -1 value for the record count.

It's just use exec or execute statement:
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnectionString
Conn.Execute "Exec sp_selectNewHireSQL"
Reference: http://msdn.microsoft.com/en-us/library/ms188332(v=sql.90).aspx

To have the RecordCount working you need to use proper cursor:
Set rsGetHireID = Server.CreateObject("ADODB.RecordSet")
Conn.Open ConnectionString
rsGetHireID.CursorLocation = 3 'adUseClient
rsGetHireID.Open "Exec sp_selectNewHireSQL", Conn
NumOfHireID = rsGetHireID.RecordCount

Instead of using ADODB.Connection, try using ADODB.Command instead like this:
Set objCommand = Server.CreateObject("ADODB.Command")
objCommand.ActiveConnection = ConnectionString
objCommand.CommandText = "dbo.sp_selectNewHireSQL"
objCommand.CommandType = adCmdStoredProc ' you have to include adovbs.inc file or you can use 4
Set rsGetHireID = objCommand.Execute()
NumOfHireID = rsGetHireID.RecordCount
Response.Write (NumOfHireID)

<%
dim db_conn
db_conn = "Provider=SQLOLEDB.1;Server=server name;Database=dbname;Uid=sa; Pwd=123;"
set conn = server.createobject("adodb.connection")
set Cmd = Server.CreateObject("ADODB.Command")
'-------------------------------------------------------
conn.open (db_conn)
'-------------------------------------------------------
set rs = Server.CreateObject("ADODB.RecordSet")
sSQL = "EXEC sp_countrylist #countryname ='" & countryname & "'"
set rs = conn.execute(sSQL)
if (rs.bof and rs.eof) then
response.Write "<span class=""error"">No Record Found</span>"
response.End
end if %>

Related

Visual Basic 6.0 ADODB command to variable

Here's the code
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.CursorLocation = adUseClient
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Nirvana.mdb" & "; Persist Security Info=False;"
Set cmd = New ADODB.Command
cmd.CommandText = "Select [Last Name] From Accounts Where [First Name]=#FN"
Set cmd.ActiveConnection = conn
cmd.Parameters.Item("#FN").Value = txtFirstName.Text
cmd.Execute
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
conn.Close
How do i pass the result of this query to a variable in Visual Basic 6.0 ?
Results are stored in a Record Set, create one:
dim rs as ADODB.RecordSet
Then instead of cmd.execute use:
rs.open cmd
if not rs.eof then
''//got rows
msgbox "first row, first col=" & rs.collect(0)
...

ASP SQL Server Connection

<%
DIM objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
objConn.Open
DIM mySQL
mySQL = "SELECT * FROM [Users] WHERE [User ID]='1'"
DIM objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.open(mySQL, objConn)
Response.Write objRS("FullName")
objRS.Close
Set objRS = Nothing
objConn.Close
Set objConn = Nothing
%>
I want to connect to a SQL Server Database, read the data and close the connection. I have studied the examples and came up with this. But its not working. Please guide me. Where am I going wrong?
Some answers have suggested wrapping logic into functions there is no need for this.
It's just a lot of fluff that isn't needed, just use the ADODB.Command object. There are hundreds of ways to approach this but a method I have found to work time and again is let the ADODB.Command object do the work then return your results into an Array using .GetRows() method of the ADODB.Recordset object.
That way you can close off both the ADODB.Recordset and ADODB.Command objects quickly and work just with the Array.
Dim conn, cmd, rs, sql, data, search
'Assume value to query comes from a Request Collection.
search = Request("myvalue") & ""
conn = "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
sql = "select from mytable where this = ?"
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
'No need to handle connection let ADODB.Command create and destory it.
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = sql
.Parameters.Append(.CreateParameter("#myparam", adVarWChar, adParamInput, 50))
.Parameters("#myparam").Value = search
Set rs = .Execute()
If Not rs.EOF Then data = rs.GetRows()
Call rs.Close()
Set rs = Nothing
End with
Set cmd = Nothing
'ADODB.Connection is closed when ADODB.Command is destroyed.
If IsArray(data) Then
rows = UBound(data, 2)
For row = 0 To rows
'Return first column of the current row
Call Response.Write("First Column of Row " & row & " is '" & data(0, row) & "'<br />"
Next
Else
Call Response.Write("No records")
End If
Dim rs, dbConn
Function OpenDB()
Set dbConn = Server.CreateObject("ADODB.Connection")
dbConn.ConnectionTimeout = 300
dbConn.CommandTimeout = 300
dbConn.Open "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
End Function
Function CloseDB()
Set rs = Nothing
if ucase(TypeName(dbConn)) = "CONNECTION" then
dbConn.Close
Set dbConn = Nothing
end if
End Function
Function OpenRecordSet(recset, tablename)
Call OpenDB()
Set recset = Server.CreateObject("ADODB.Recordset")
recset.Open tablename, dbConn, 0, 1
End Function
Function CloseRecordSet(recset)
Set recset = Nothing
Call CloseDB()
End Function
Then use
<%
Call OpenDB()
sql = "select from mytable where this = 'that'"
Set rs = dbConn.Execute(sql)
if not rs.EOF then
' do your stuff!
end if
Call CloseDB()
%>
http://www.shiningstar.net/articles/articles/database/datafunctions.asp?ID=AW

Connecting to sql server 2008 using vb

Function DBConnect()
Dim vConnString, wfConnection, objConn
set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open Application("DB_CONNECT")
set DBConnect = objConn
exit function
Response.Write("connected to Server 2008")
End Function
Function GetValue()
Dim objCmd, objRS
Set objCMD = Server.CreateObject("ADODB.Command")
Set objRs = Server.CreateObject("ADODB.Recordset")
With (objCMD)
.ActiveConnection = DBConnect()
.CommandType = adCmdStoredProc
.CommandText = "select * from Acc.dbo.table"
set ObjRS = .Execute()
End With
if err.number = 0 then
if not objRs.EOF then
arrData = objRs.GetRows
vDesc = arrData(5,0)
else
vDesc = vValue
end if
GetDescFromCode = True
end if
Response is Coming as
connected to Server 2008
While debuging, i got that its not going inside objRs.EOF if loop...any idea whats wrong
In DBConnect, check the status of objConn to make sure it's really being opened.
In DBConnect, you have exit function before response.write.
In GetValue, check value of err.number.

ASP page not displaying Stored Procedure OUTPUT

I have an ASP page calling a stored procedure with returned values AND OUTPUT parameters.
The output parameters aren't displaying and I'm not understanding why:
<%
dim Objrs, cmd
set Objrs = Server.CreateObject("ADODB.RecordSet")
set cmd = Server.CreateObject("ADODB.Command")
set conn = Server.CreateObject("ADODB.Connection")
conn.Open strConnect
set cmd.ActiveConnection = conn
cmd.CommandText="MKTG_Current"
cmd.CommandType=adCmdStoredProc
cmd.Parameters.Append cmd.CreateParameter("#added", 135, 2)
cmd.Parameters.Append cmd.CreateParameter("#named", 200, 2, 50)
set Objrs = cmd.Execute
%>
</div>
<div id="recent-news-box" class="rounded-corners-top dropshadow">
<h3 class="border-dashed-b">Updated on: <%=Objrs.state%></h3>
<div>
<%
While Not Objrs.EOF
Response.Write Objrs("Subject")
Objrs.MoveNext
Wend
name_of_table = cmd.Parameters("#named").value
added = cmd.Parameters("#added").value
set cmd = nothing
set Objrs = nothing
conn.close
set conn = nothing
Response.Write name_of_table
Response.Write added
%>
</div>
</div>
</div>
I've tried changing the position of the output items to no avail.
There is some clunkiness because of the way ADO returns command results to both a recordset and as output paramaters.
They are available after the returned recordset is closed, so this order should work:
set Objrs = nothing
name_of_table = cmd.Parameters("#named").value
added = cmd.Parameters("#added").value
set cmd = nothing
conn.close
set conn = nothing
Response.Write name_of_table
Response.Write added
An alternative is to leave the code as it is add switch to a client side cursor with:
conn.Open strConnect
conn.CursorLocation = 3 '//aduseclient
set cmd.ActiveConnection = conn
(Also check that your use of adCmdStoredProc should not be replaced with its numeric value if your not linked to a typelib)

VBScript how to set the connection string

I am not sure whether it has been disscussed before or not but I have the following code (I changed from example for an Access database.)
I don't know what to put inside the 'Provider' and the 'Data Source'. I'm using MS SQL Server 2005 and how to find this information in my machine? Please, even I try to follow from here http://www.connectionstrings.com/, yet I still don't know how to do it.
Dim conn, sql
sql = "SELECT * FROM tblOutbox"
Set conn = CreateObject("ADODB.Connection")
With conn
.Provider = "myProvider"
.Mode = adModeReadWrite
.ConnectionString = "Data Source=mysource;" & _
"database=myDbase.mdf; "
.Open
End With
If conn.State = adStateOpen Then
WScript.Echo "Connection was established."
End If
conn.Close
Set conn = Nothing
here is using access database:
Dim conn
Dim sql
sql = "SELECT * FROM tblOutbox"
Set conn = CreateObject("ADODB.Connection")
With conn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Mode = adModeReadWrite
.ConnectionString = "Data Source= f:/Status.mdb"
.Open
End With
WScript.Echo "Connection was opened."
conn.Close
Set conn = Nothing
WScript.Echo "Connection was closed."
Try setting the provider in the connection string
conn.ConnectionString = "Provider=SQLOLEDB.1;Data Source=XXX;Initial Catalog=XXX;User ID=<XXX>;Password=<XXX>;"
Note: I haven't tested it but it should work
For all your connection string needs: http://www.connectionstrings.com/
I finally found the solution thanks to your help.
Under the Administrative Tools, Data Source (ODBS), driver tabs, I use provider: SQLNCLI, my Server: Data Source, and I add Recordset rs to the code. It seems that, without this one, the connection is not established. I don't know what happened.
Dim conn , rs, sql, ConnString
sql = "SELECT * FROM tblOutbox"
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
With conn
.Provider = "SQLNCLI"
.Mode = adModeReadWrite
.ConnectionString = "SERVER=.\SQLExpress;AttachDbFilename=F:\Test2.mdf;Database=Test2.mdf; Trusted_Connection=Yes;"
.Open
WScript.Echo "Connection was established."
End With
rs.Open sql,conn
If conn.State = adStateOpen Then
WScript.Echo "Connection was established."
Else
WScript.Echo "No Connection ."
End If
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
With SQL Server you don't connect directly to the file. Access, being a file-based RDBMS is a little different.
Following your example, it would look something like this:
Dim conn, sql
sql = "SELECT * FROM tblOutbox"
Set conn = CreateObject("ADODB.Connection")
With conn
.Mode = adModeReadWrite
.ConnectionString = "Provider=SQLOLEDB;server=[servername];database=[databasename]uid=[insertuser];pwd=[insertpassword];"
.Open
End With
If conn.State = adStateOpen Then
WScript.Echo "Connection was established."
End If
conn.Close
Set conn = Nothing
There's usually a more compact way of doing this, but without the context its hard to give a better example