Link to home
Start Free TrialLog in
Avatar of kaiwhoeatspie
kaiwhoeatspieFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Error when executing a Stored Procedure and returning a value

Hi,

Can anyone help? I have added a function (see below) that is called from ASP pages. The function should execute a Stored Procedure in SQL Server 2000 that returns the next available key value for a given table name. The function is called as:

lnKeyValue = getkey("<a table name>")

I know that the Stored Procedure works because it returns the "lastkeyval" value in SQL Query Analalzer. However I get the following error:

ADODB.Recordset error '800a0cc1'

Item cannot be found in the collection corresponding to the requested name or ordinal.

"connectConn" calls another function. I know the Stored Procedure works because it successfully updates another table.

The problem I encounter is returning the value "getKey".

Here is the function:

###################################################################
<%
function getKey(lparam1)

     Dim lctablename, rs, adocmd
 
     lctablename = trim(lparam1)
     
     set rs = connectConn.Execute("EXEC sp_getkey '" & lcTableName & "'")

'**** ERROR OCCURS IN THIS LINE ****
     getKey = rs("lastkeyval")
'***********************************
     
     set rs = nothing

     destroyConn()

end function
%>
###################################################################

Thanks!
Avatar of arthuryeung
arthuryeung

can you post out the code in your stored procedure as well, i think the problem should be related to the store procedure rather than the ASP
Hi

...Item cannot be found in the collection corresponding to the requested name or ordinal....

 this error message simply means that you are entering incorrect field name in the sql statement. cross check the name of returnvalues in your asp code e.g. lastkeyval and the field names of your tables.

cheers!!
i mean to say that please check whether sp_getkey is returning a recordset or not, and that recordset contains a field named as lastkeyval or not.
try to use getkey=rs.fields(0)
that's why i think he got to post out the source code for the store procedure, he still didn't mention whether he return the value from "Return value" , "output parameter" or "recordset".

3 different way of returning method have 3 different way to get it. so got to see his code before we know how to help
Avatar of kaiwhoeatspie

ASKER

Here is the code for the tored Procedure.

CREATE PROCEDURE sp_getkey @tablename VARCHAR(32) OUTPUT as
     DECLARE @NextId INTEGER
     DECLARE @SQLReturn INTEGER
     BEGIN
     begin tran spgetkey
     /*  begin tran
     save transaction getkey */
     UPDATE keymast
     SET lastkeyval = lastkeyval + 1
     WHERE tablename = @tablename
     IF @@rowcount = 0
          BEGIN
        commit tran spgetkey
               /* rollback getkey commit tran */
               SELECT @tablename = (SELECT UPPER(@tablename))
               /* raiserror 99999 'Key generation error: Cannot increment key value for "%1!"',@tablename */
               raiserror('Key generation error: Cannot increment key value for "%1!"', 16,-1, @tablename)
               RETURN -1
          END
     ELSE
          BEGIN
               SELECT lastkeyval
                 FROM keymast
                WHERE tablename = @tablename
               SELECT @tablename = convert(varchar(32), lastkeyval )
                 FROM keymast
                WHERE tablename = @tablename
 
               commit tran spgetkey
        /* COMMIT tran */
          END
     END

GO
When I run the above Stored Procedure in SQL Query Analyzer (e.g. EXECUTE sp_getkey 'CLog') I get a resulting table with one fieldname "lastkeyval" and a one-record result (integer value). I would have thought
rs("lastkeyval") would return that value but somehow it doesn't. I tried rs.fields(0) as well but that didn't work either.

I can guarantee that the Stored Procedure works as it is. We've been calling it from some FoxPro code for years.

Any ideas?
When I run the above Stored Procedure in SQL Query Analyzer (e.g. EXECUTE sp_getkey 'CLog') I get a resulting table with one fieldname "lastkeyval" and a one-record result (integer value). I would have thought
rs("lastkeyval") would return that value but somehow it doesn't. I tried rs.fields(0) as well but that didn't work either.

I can guarantee that the Stored Procedure works as it is. We've been calling it from some FoxPro code for years.

Any ideas?
I think you should consider using OUTPUT parameters to output lastkeyval instead of getting the recordset. This is the problem of ADO, especially you have been calling more than one SELECT statments inside the stored procedure.

Try modifying your stored procedure like this:

CREATE PROCEDURE sp_getkey
    @tablename VARCHAR(32) OUTPUT,
    @lastkeyval INTEGER OUTPUT
    as
    DECLARE @NextId INTEGER
    DECLARE @SQLReturn INTEGER
    BEGIN
    begin tran spgetkey
    /*  begin tran
    save transaction getkey */
    UPDATE keymast
    SET lastkeyval = lastkeyval + 1
    WHERE tablename = @tablename
    IF @@rowcount = 0
         BEGIN
       commit tran spgetkey
              /* rollback getkey commit tran */
              SELECT @tablename = (SELECT UPPER(@tablename))
              /* raiserror 99999 'Key generation error: Cannot increment key value for "%1!"',@tablename */
              raiserror('Key generation error: Cannot increment key value for "%1!"', 16,-1, @tablename)
              RETURN -1
         END
    ELSE
         BEGIN
              SELECT @lastkeyval = lastkeyval
                FROM keymast
               WHERE tablename = @tablename
              SELECT @tablename = convert(varchar(32), lastkeyval )
                FROM keymast
               WHERE tablename = @tablename

              commit tran spgetkey
       /* COMMIT tran */
         END
    END

GO

And your ASP like this:
<%
    set objComm = Server.CreateObject("ADODB.Command")
    objComm.ActiveConnection = connectConn
    objComm.CommandText = "sp_getkey"
    objComm.CommandType = adCmdStoredProc
    objComm.Parameters.Append objComm.CreateParameter("Return", adInteger, adParamReturnValue)
    objComm.Parameters.Append objComm.CreateParameter("@tablename", adChar, adParamOutput, 32, tablename)
    objComm.Parameters.Append objComm.CreateParameter("@lastkeyval", adDouble, adParamOutput, , lastkeyval_no)
    objComm.Execute
    return = cint(objComm.Parameters("Return"))
    lastkeyval = objComm.Parameters("@lastkeyval")
    set objComm = nothing
%>
i made a typo, the ASP code should be:

<%
   set objComm = Server.CreateObject("ADODB.Command")
   objComm.ActiveConnection = connectConn
   objComm.CommandText = "sp_getkey"
   objComm.CommandType = adCmdStoredProc
   objComm.Parameters.Append objComm.CreateParameter("Return", adInteger, adParamReturnValue)
   objComm.Parameters.Append objComm.CreateParameter("@tablename", adChar, adParamOutput, 32, tablename)
   objComm.Parameters.Append objComm.CreateParameter("@lastkeyval", adDouble, adParamOutput, , lastkeyval)
   objComm.Execute
   return = cint(objComm.Parameters("Return"))
   lastkeyval = objComm.Parameters("@lastkeyval")
   set objComm = nothing
%>
Thanks arthuryeung, I'll try and get back to you.

By the way, is there any advantage using ADODB.Command and parameters rather than a simple "set rs = connection.Execute("execute <stored procedure>")?
using ADODB command , you can also get the OUTPUT parameters, RETURN parameters.

using ("set rs = connection.Execute("execute <stored procedure>"), your can only get the first return recordset and the behaviour is difficult to predict while you have more than one SELECT query inside the stored procedure.

you can't say which method is better than the other, if my store procedure is just one single SELECT statement, i will just the later method, which if it is more complicated i will do the first
Unfortunately I get the following error:

Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.

It occurs in line:

objComm.Parameters.Append objComm.CreateParameter("Return", adInteger, adParamReturnValue)

By the way shouldn't it be:
objComm.Parameters.Append objComm.CreateParameter("@tablename", adChar, adParamInput, 32, tablename)

instead of adParamOutput? I want to input the tablename and output lastkeyval.

actually, i put @tablename as AdParamOutput because i see this line from your code:

CREATE PROCEDURE sp_getkey @tablename VARCHAR(32) OUTPUT as

if you want to input tablename and output lastkeyval the header should be

CREATE PROCEDURE sp_getkey
   @tablename [VARCHAR](32),
   @lastkeyval [int] OUTPUT
   as

This line should be ok:
objComm.Parameters.Append objComm.CreateParameter("Return", adInteger, adParamReturnValue)

maybe the problem is :
objComm.CommandType = adCmdStoredProc

have you check whether you have the constant adCmdStoredProc defined ? try to response.write it out to see whether it has value or not

It has no value.
save the following content into a file called adoconst.inc:

<%
'--------------------------------------------------------------------
' Microsoft ADO
'
' (c) 1996 Microsoft Corporation.  All Rights Reserved.
'
'
'
' ADO constants include file for VBScript
'
'--------------------------------------------------------------------

'---- 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
Const adNotify = &H00040000

'---- LockTypeEnum Values ----
Const adLockReadOnly = 1
Const adLockPessimistic = 2
Const adLockOptimistic = 3
Const adLockBatchOptimistic = 4

'---- ExecuteOptionEnum Values ----
Const adRunAsync = &H00000010

'---- ObjectStateEnum Values ----
Const adStateClosed = &H00000000
Const adStateOpen = &H00000001
Const adStateConnecting = &H00000002
Const adStateExecuting = &H00000004

'---- CursorLocationEnum Values ----
Const adUseNone = 1
Const adUseServer = 2
Const adUseClient = 3
Const adUseClientBatch = 3

'---- DataTypeEnum Values ----
Const adEmpty = 0
Const adTinyInt = 16
Const adSmallInt = 2
Const adInteger = 3
Const adBigInt = 20
Const adUnsignedTinyInt = 17
Const adUnsignedSmallInt = 18
Const adUnsignedInt = 19
Const adUnsignedBigInt = 21
Const adSingle = 4
Const adDouble = 5
Const adCurrency = 6
Const adDecimal = 14
Const adNumeric = 131
Const adBoolean = 11
Const adError = 10
Const adUserDefined = 132
Const adVariant = 12
Const adIDispatch = 9
Const adIUnknown = 13
Const adGUID = 72
Const adDate = 7
Const adDBDate = 133
Const adDBTime = 134
Const adDBTimeStamp = 135
Const adBSTR = 8
Const adChar = 129
Const adVarChar = 200
Const adLongVarChar = 201
Const adWChar = 130
Const adVarWChar = 202
Const adLongVarWChar = 203
Const adBinary = 128
Const adVarBinary = 204
Const adLongVarBinary = 205

'---- FieldAttributeEnum Values ----
Const adFldMayDefer = &H00000002
Const adFldUpdatable = &H00000004
Const adFldUnknownUpdatable = &H00000008
Const adFldFixed = &H00000010
Const adFldIsNullable = &H00000020
Const adFldMayBeNull = &H00000040
Const adFldLong = &H00000080
Const adFldRowID = &H00000100
Const adFldRowVersion = &H00000200
Const adFldCacheDeferred = &H00001000

'---- EditModeEnum Values ----
Const adEditNone = &H0000
Const adEditInProgress = &H0001
Const adEditAdd = &H0002

'---- RecordStatusEnum Values ----
Const adRecOK = &H0000000
Const adRecNew = &H0000001
Const adRecModified = &H0000002
Const adRecDeleted = &H0000004
Const adRecUnmodified = &H0000008
Const adRecInvalid = &H0000010
Const adRecMultipleChanges = &H0000040
Const adRecPendingChanges = &H0000080
Const adRecCanceled = &H0000100
Const adRecCantRelease = &H0000400
Const adRecConcurrencyViolation = &H0000800
Const adRecIntegrityViolation = &H0001000
Const adRecMaxChangesExceeded = &H0002000
Const adRecObjectOpen = &H0004000
Const adRecOutOfMemory = &H0008000
Const adRecPermissionDenied = &H0010000
Const adRecSchemaViolation = &H0020000
Const adRecDBDeleted = &H0040000

'---- GetRowsOptionEnum Values ----
Const adGetRowsRest = -1

'---- PositionEnum Values ----
Const adPosUnknown = -1
Const adPosBOF = -2
Const adPosEOF = -3

'---- enum Values ----
Const adBookmarkCurrent = 0
Const adBookmarkFirst = 1
Const adBookmarkLast = 2

'---- MarshalOptionsEnum Values ----
Const adMarshalAll = 0
Const adMarshalModifiedOnly = 1

'---- AffectEnum Values ----
Const adAffectCurrent = 1
Const adAffectGroup = 2
Const adAffectAll = 3

'---- FilterGroupEnum Values ----
Const adFilterNone = 0
Const adFilterPendingRecords = 1
Const adFilterAffectedRecords = 2
Const adFilterFetchedRecords = 3
Const adFilterPredicate = 4

'---- SearchDirection Values ----
Const adSearchForward = 0
Const adSearchBackward = 1

'---- ConnectPromptEnum Values ----
Const adPromptAlways = 1
Const adPromptComplete = 2
Const adPromptCompleteRequired = 3
Const adPromptNever = 4

'---- ConnectModeEnum Values ----
Const adModeUnknown = 0
Const adModeRead = 1
Const adModeWrite = 2
Const adModeReadWrite = 3
Const adModeShareDenyRead = 4
Const adModeShareDenyWrite = 8
Const adModeShareExclusive = &Hc
Const adModeShareDenyNone = &H10

'---- IsolationLevelEnum Values ----
Const adXactUnspecified = &Hffffffff
Const adXactChaos = &H00000010
Const adXactReadUncommitted = &H00000100
Const adXactBrowse = &H00000100
Const adXactCursorStability = &H00001000
Const adXactReadCommitted = &H00001000
Const adXactRepeatableRead = &H00010000
Const adXactSerializable = &H00100000
Const adXactIsolated = &H00100000

'---- XactAttributeEnum Values ----
Const adXactCommitRetaining = &H00020000
Const adXactAbortRetaining = &H00040000

'---- PropertyAttributesEnum Values ----
Const adPropNotSupported = &H0000
Const adPropRequired = &H0001
Const adPropOptional = &H0002
Const adPropRead = &H0200
Const adPropWrite = &H0400

'---- ErrorValueEnum Values ----
Const adErrInvalidArgument = &Hbb9
Const adErrNoCurrentRecord = &Hbcd
Const adErrIllegalOperation = &Hc93
Const adErrInTransaction = &Hcae
Const adErrFeatureNotAvailable = &Hcb3
Const adErrItemNotFound = &Hcc1
Const adErrObjectInCollection = &Hd27
Const adErrObjectNotSet = &Hd5c
Const adErrDataConversion = &Hd5d
Const adErrObjectClosed = &He78
Const adErrObjectOpen = &He79
Const adErrProviderNotFound = &He7a
Const adErrBoundToCommand = &He7b
Const adErrInvalidParamInfo = &He7c
Const adErrInvalidConnection = &He7d
Const adErrStillExecuting = &He7f
Const adErrStillConnecting = &He81

'---- ParameterAttributesEnum Values ----
Const adParamSigned = &H0010
Const adParamNullable = &H0040
Const adParamLong = &H0080

'---- ParameterDirectionEnum Values ----
Const adParamUnknown = &H0000
Const adParamInput = &H0001
Const adParamOutput = &H0002
Const adParamInputOutput = &H0003
Const adParamReturnValue = &H0004

'---- CommandTypeEnum Values ----
Const adCmdUnknown = &H0008
Const adCmdText = &H0001
Const adCmdTable = &H0002
Const adCmdStoredProc = &H0004

'---- SchemaEnum Values ----
Const adSchemaProviderSpecific = -1
Const adSchemaAsserts = 0
Const adSchemaCatalogs = 1
Const adSchemaCharacterSets = 2
Const adSchemaCollations = 3
Const adSchemaColumns = 4
Const adSchemaCheckConstraints = 5
Const adSchemaConstraintColumnUsage = 6
Const adSchemaConstraintTableUsage = 7
Const adSchemaKeyColumnUsage = 8
Const adSchemaReferentialContraints = 9
Const adSchemaTableConstraints = 10
Const adSchemaColumnsDomainUsage = 11
Const adSchemaIndexes = 12
Const adSchemaColumnPrivileges = 13
Const adSchemaTablePrivileges = 14
Const adSchemaUsagePrivileges = 15
Const adSchemaProcedures = 16
Const adSchemaSchemata = 17
Const adSchemaSQLLanguages = 18
Const adSchemaStatistics = 19
Const adSchemaTables = 20
Const adSchemaTranslations = 21
Const adSchemaProviderTypes = 22
Const adSchemaViews = 23
Const adSchemaViewColumnUsage = 24
Const adSchemaViewTableUsage = 25
Const adSchemaProcedureParameters = 26
Const adSchemaForeignKeys = 27
Const adSchemaPrimaryKeys = 28
Const adSchemaProcedureColumns = 29
%>

add a server side include in your code:
<!--#INCLUDE VIRTUAL="adoconst.inc"-->

or maybe you can just copy all the ado constants used in the above code only, for example:
<%
Const adCmdStoredProc = &H0004
Const adInteger = 3
....
....
....
%>
Thanks, that seems to have got rid of that particular error.

What's the difference between
<!--#INCLUDE VIRTUAL="adoconst.inc"--> and
<!--#INCLUDE FILE="adoconst.inc"-->? "VIRTUAL" doesn't work so I put in FILE. Is VIRTUAL more secure?

I now get this error:

Microsoft OLE DB Provider for SQL Server error '80040e14'

Syntax error or access violation

The line is:
objComm.Execute

Here is all my current code:

function getKey(lparam1)

     Dim lctablename
 
     lctablename = trim(lparam1)
     
     set objComm = Server.CreateObject("ADODB.Command")
     objComm.ActiveConnection = connectConn
     objComm.CommandText = "sp_getkey3 '" & lctablename  & "'"
     objComm.CommandType = adCmdStoredProc
     objComm.Parameters.Append objComm.CreateParameter("Return", adInteger, adParamReturnValue)
     objComm.Parameters.Append objComm.CreateParameter("@lastkeyval", adInteger, adParamOutput, , lastkeyval)
     objComm.Execute
     return = cint(objComm.Parameters("Return"))
     lastkeyval = objComm.Parameters("@lastkeyval")
     set objComm = nothing

     getKey = lastkeyval

end function

Stored Procedure:
CREATE PROCEDURE sp_getkey3
   @tablename VARCHAR(32),
   @lastkeyval INTEGER OUTPUT
   as
   DECLARE @NextId INTEGER
   DECLARE @SQLReturn INTEGER
   BEGIN
   begin tran spgetkey
   /*  begin tran
   save transaction getkey */
   UPDATE keymast
   SET lastkeyval = lastkeyval + 1
   WHERE tablename = @tablename
   IF @@rowcount = 0
        BEGIN
      commit tran spgetkey
             /* rollback getkey commit tran */
             SELECT @tablename = (SELECT UPPER(@tablename))
             /* raiserror 99999 'Key generation error: Cannot increment key value for "%1!"',@tablename */
             raiserror('Key generation error: Cannot increment key value for "%1!"', 16,-1, @tablename)
             RETURN -1
        END
   ELSE
        BEGIN
             SELECT @lastkeyval = lastkeyval
               FROM keymast
              WHERE tablename = @tablename
             SELECT @tablename = convert(varchar(32), lastkeyval )
               FROM keymast
              WHERE tablename = @tablename

             commit tran spgetkey
      /* COMMIT tran */
        END
   END
GO


Could it have something to do with the connection?
ASKER CERTIFIED SOLUTION
Avatar of arthuryeung
arthuryeung

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
arthuryeung, you deserve all 500 points. Thank you! It worked perfectly.

Now that you have shown me it makes complete sense.
thanks.

the ADODB.Command is quite powerful when you are familiar with the usage of it. it can almost do everything you need with you SQL server, i am also just a starter of using it.

it is in fact more complicated than other ADO objects when you decided to use it, but the features are more complete