views:

453

answers:

3

Hi All,

This function inserts a row into a SQL database and needs to return the identity number created:

Function WriteDatabase(backupTypeID, numImages, folderSize, success, errorMessage, strLogFileName)

    On Error Resume Next
    err.clear
    Set objConnection = CreateObject("ADODB.Connection")
    Set objRecordSet = CreateObject("ADODB.Recordset")
    objConnection.Open "Provider=SQLOLEDB;Data Source=x.x.x.x;Initial Catalog=DB;User ID=sa;Password=xxxxxx"
    sqlquery = "INSERT INTO tblImageCopies (BackupCopyDate, BackupCopyTypeID, NumImages, ImagesFolderSize, Success, ErrorMessage) VALUES (GETDATE(), " & backupTypeID & ", " & numImages & ", " & folderSize & ", " & success & ", " & errorMessage & "); SELECT scope_identity() AS ImageCopyID;" 
    objRecordSet.Open sqlquery,objConnection
    objRecordSet.MoveFirst
    WriteDatabase = objRecordSet("ImageCopyID")
    objRecordSet.Close
    objConnection.Close
    If err.number <> 0 Then
     WriteLog "Error writing to the EHN database - " & err.number & " " & err.description, strLogFileName
    End If

End Function

It successfully inserts the row, but I get the error message '3704 Operation is not allowed when the object is closed.' when it tries to return the identity number in the record set. When I execute this sql query directly on the server, it works. Anyone able to help?

+1  A: 

I do the same thing (very similar anyway). I believe that there are two sets of results coming back, one for the INSERT and then another for the SELECT. Try calling objRecordSet.NextRecordset().

Brian
Thanks Brian. Can you please advise exactly where I should put objRecordSet.NextRecordSet()? I've tried a couple of places but it's still erroring, I believe you're on the right track tho.
VBscripter
Ok figured it out, I had to remove objRecordset.MoveFirst and replace it with Set objRecordSet2 = objRecordSet.NextRecordset(), then change the return line to WriteDatabase = objRecordSet2("ImageCopyID"). I also had to remove objRecordset.Close. As the first statement in my compound statement does not return any rows (its an INSERT statement), objRecordset is automatically closed and cannot be closed again, thus generating the error.
VBscripter
A: 

Eu quero saber que erro é esse por que eu não estou conseguindo fazer a inscrição do PROUNI, estou na 3º etapa e os dados do meu pai não estar dando certo.

Pollyane Mayara Frutuoso Fonse