I have the following script in ASP Classic:
<%# LANGUAGE=Javascript%>
<%
var dataConn = Server.CreateObject('ADODB.Connection');
dataConn.Open(connectionString);
var rowsAffected;
dataConn.Execute(command, rowsAffected);
Response.Write(rowsAffected);
dataConn.Close();
%>
When executing the script rowsAffected is undefined. How to get the affected rows?
After searching the web I found an answer that JScript does not support ByRef variables to get the affected rows. It only works in VBScript.
So I use the following script to get the affected rows from my stored procedure:
<!--METADATA TYPE="TypeLib" NAME="Microsoft ActiveX Data Objects 2.6 Library" UUID="{00000206-0000-0010-8000-00AA006D2EA4}" VERSION="2.6" -->
<%# LANGUAGE=JScript%>
<%
var cn = Server.CreateObject('ADODB.Connection');
var cs = '...';
cn.Open(cs); cn.CursorLocation = adUseClient;
var cmd = Server.CreateObject("ADODB.Command");
cmd.ActiveConnection = cn;
cmd.CommandText = '...';
cmd.CommandType = adCmdStoredProc;
cmd.Parameters.Append(cmd.CreateParameter('#ID', adInteger, adParamInput, 4, id));
cmd.Parameters.Append(cmd.CreateParameter('#RowCount', adInteger, adParamOutput, 4));
cmd.Execute(adExecuteNoRecords);
Response.Write(cmd.Parameters('#RowCount').Value);
cn.Close();
%>
And you need a stored procedure like this:
CREATE PROC dbo.<StoredProcedure> #ID int, #RowCount int = 0 output AS BEGIN
[...]
SET #RowCount = ##rowcount;
END
Related
Can someone point me in the right direction for information on how to push data to Active Directory from Classic ASP?
There are a couple of ways this can be done from classic ASP.
Use ADO with ADSI
Use the ADSI Objects of LDAP
Here's a sample from Modifying an ADSI Object from ADO
'Replace department for all users in OU=sales.
Set con = Server.CreateObject("ADODB.Connection")
con.Provider = "ADsDSOObject"
Set command = CreateObject("ADODB.Command")
Set command.ActiveConnection = con
command.CommandText = "SELECT AdsPath, cn FROM 'LDAP://OU=Sales,DC=Fabrikam,DC=com' WHERE objectClass = 'user'"
command.Properties("searchscope") = ADS_SCOPE_ONELEVEL
Set rs = command.Execute
While Not rs.EOF
Set usr = GetObject(rs.Fields("AdsPath").Value)
usr.Put "department", "1001"
usr.SetInfo
rs.MoveNext
Wend
Here's a sample from the article Getting Started with ASP for ADSI.
<%# Language=VBScript %>
<%
' Get the inputs.
containerName = Request.Form("inpContainer")
' Validate compName before using.
If Not ("" = containerName) Then
' Bind to the object.
adsPath = "LDAP://" & containerName
Set comp = GetObject(adsPath)
' Write the ADsPath of each of the child objects.
Response.Write("<p>Enumeration:</p>")
For Each obj in comp
Response.Write(obj.ADsPath + "<BR>")
Next
End If
%>
I am trying to execute a stored procedure using Classic ASP, with two parameters and return the results into a record set that I can loop through and display into a table via a DO WHILE loop.
The problem is, however, I do not get any results when I try and execute the below code. When I use the "RecordCount" property it returns -1 records.
Normally if it were a standard SQL query I would use Response.Write to get the query text and diagnose in SSMS, but i'm not sure how I can troubleshoot when using ADODB.Command. Is there a way to write out exactly what it is doing?
Here is what I have:
Set cmd = Server.CreateObject("ADODB.Command")
Set objRS = Server.CreateObject("ADODB.RecordSet")
With cmd
.ActiveConnection = objConn
.CommandType = 4
.CommandText = "dbo.testCount"
Call .Parameters.Append(.CreateParameter("#Location", adVarChar, adParamInput, 50))
Call .Parameters.Append(.CreateParameter("#Year", adInteger, adParamInput))
.Parameters("#Location").Value = "TestLocation"
.Parameters("#Year").Value = 2014
Set objRS = cmd.Execute()
End With
Set cmd = Nothing
TotalRecords = objRS.RecordCount
Response.Write TotalRecords
^^^^ TotalRecords = "-1" .. ?
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
I've been searching the depths of the internet and all the solutions I found did not solve this problem.
I am using Visual Web Developer 2010 Express with SQL Server 2008, using VB.
I am trying to execute a stored procedure to insert some data coming from a textbox control to a database, if the id doesn't exist it inserts both the id given in the textbox and the current date (time_scanned_in), if the id exists already, it will insert the current datetime in the [time_scanned_out] column, if all 3 fields in the db are full, it will return #message = 1.
Here is the sql stored procedure:
ALTER PROCEDURE dbo.InsertDateTime
#barcode_id nchar(20),
#message char(1) = 0 Output
AS
BEGIN
if not exists(select * from tblWork where barcode_id = #barcode_id)
begin
INSERT INTO [tblWork] ([barcode_id], [time_scanned]) VALUES (#barcode_id, GetDate())
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NOT NULL )
begin
SET #message=1
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NULL)
begin
UPDATE [tblWork] SET [time_scanned_out] = GetDate() WHERE [barcode_id] = #barcode_id
end
RETURN #message
end
If I execute this (by right clicking on the SP), it works flawlessly and returns the values when all fields have been filled.
But when executed through the vb code, no such procedure can be found, giving the error in the title.
Here is the vb code:
Dim opconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim sqlConnection1 As New SqlConnection(opconn)
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "InsertDateTime"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
With cmd.Parameters.Add(New SqlParameter("#barcode_id", TextBox.Text))
End With
With cmd.Parameters.Add(New SqlParameter("#message", SqlDbType.Char, 1, Label3.Text))
End With
returnValue = cmd.ExecuteScalar()
sqlConnection1.Close()
Note, I haven't done the code for the return part yet, will do that once I get it to locate the SP.
Tried listing all objects with the sys.objects.name for each of the databases in a gridview, it listed everything but the stored procedure I want.
Why is this, any ideas? Would be much appreciated, spent hours trying to find a solution.
If anyone needs any more code or information feel free to ask.
try cmd.parameters.clear() first and then start adding parameters in cmd object. also instead of cmd.executescaler(), try cmd.executenonquery or cmd.executeReader()
Try this
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
SqlParameter prmOut = cmd.Parameters.Add("#message",SqlDbType.Char, 1)
prmOut.Value = Label3.Text
prmOut.Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
returnValue = prmOut.Value.ToString()
Recreated the whole project with a whole new database, copied all the same code, and now it all works flawlessly! Still have no idea what was wrong, but thank you all, you were all prompt and knowledgable.
Here was the final VB code for anyone who's interested:
Dim myConnection As New SqlConnection(opconn)
Dim cmd As New SqlCommand()
Dim myReader As SqlDataReader
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = myConnection
cmd.CommandText = "InsertTimes"
cmd.Parameters.AddWithValue("#message", OleDbType.Integer)
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
cmd.Parameters("#message").Direction = ParameterDirection.Output
Try
myConnection.Open()
myReader = cmd.ExecuteReader()
Dim returnMessage As String = cmd.Parameters("#message").Value
If returnMessage = 1 Then
label_confirmation.Text = "Record successfully submitted!"
TextBox.Text = ""
ElseIf returnMessage = 2 Then
label_confirmation.Text = "A finish time already exists for the record '" & TextBox.Text & "', would you like to override the finish time anyway?"
button_yes.Visible = True
button_no.Visible = True
ElseIf returnMessage = 3 Then
label_confirmation.Text = "Record submitted, work operation status complete!"
TextBox.Text = ""
End If
Catch ex As Exception
label_confirmation.Text = ex.ToString()
Finally
myConnection.Close()
End Try
I've written a simple form handler script using ASP3.0/VBScript and would like to add the inputted data (via the web) to an Access database located on my server. I'm using the OLEDB method to connect like so:
Cst = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"DATA SOURCE=" & Server.MapPath("DataBase.mdb")
Dim Conn
Set Conn = CreateObject("ADODB.Connection")
Conn.Mode = 3
Conn.Open Cst
Blah Blah Blah...
I currently have a file named ADOVBS.inc included at the top but would like to ditch it because I feel it's inefficient and wasteful. I'd like to define the constants as I need them- but I don't know how. What ADO constants would I need to define and where? The book that I'm using basically says "forget about that- pound include those 400 or so boogers in there and don't ask stupid questions!"
Any specific examples/help would be greatly appreciated.
Thanks,
you have a couple of options to choose from. You can reference the metadata library in your page ( or in your global.asa file ) with
<!--
METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.5 Library"
UUID="{00000205-0000-0010-8000-00AA006D2EA4}"
VERSION="2.5"
-->
or
you can simply copy a few constants from the adovbs file into your page to cover your needs. For example
Const adCmdText = 1 'Evaluate as a textual definition
Const adCmdStoredProc = 4 'Evaluate as a stored procedure
Of course that the answer is "Forget about that- pound include those 400 or so boogers in there and don't ask stupid questions!" :)
But since you insist:
The best way is to encapsulate all data access function in one .ASP
Let's call it dbHelper.asp
Then put all the DB functions in there, like:
''// run a query and returns a disconnected recordset
Function RunSQLReturnRS(sqlstmt, params())
On Error Resume next
''//Create the ADO objects
Dim rs , cmd
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
''// Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = sqlstmt
cmd.CommandType = adCmdText
collectParams cmd, params
''//Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
If err.number > 0 then
BuildErrorMessage()
exit function
end if
''//Disconnect the recordset
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
''//Return the resultant recordset
Set RunSQLReturnRS = rs
End Function
At that point, you know that all you ado constants are in this file and you can start replacing them as wished.
Relevant list of constants can be found here: https://web.archive.org/web/20190225142339/http://www.4guysfromrolla.com:80/ASPScripts/PrintPage.asp?REF=/webtech/faq/beginner/faq7.shtml
I'll copy it here as well:
'---- CursorTypeEnum Values ----
Const adOpenForwardOnly = 0
Const adOpenKeyset = 1
Const adOpenDynamic = 2
Const adOpenStatic = 3
'---- CursorOptionEnum Values ----
Const adHoldRecords = &H00000100
Const adMovePrevious = &H00000200
Const adAddNew = &H01000400
Const adDelete = &H01000800
Const adUpdate = &H01008000
Const adBookmark = &H00002000
Const adApproxPosition = &H00004000
Const adUpdateBatch = &H00010000
Const adResync = &H00020000
Should be enough for inserting/selecting/updating records in database.