CurrentProject.Connection.Execute(strSQL) immediately produces failed connection error

I have created a SQL statement using code that I want to run using Set 'variable' = currentproject.connection.execute(strSQL).

In case, I immediately receive the error "run-time error '-2147467259 (800004005)': Method 'Execute of object '_connection' failed.

A similar line of code works in this module fine and if I cut and paste the strSQL statement from the debug window to a query, the query runs fine.  

I'm a little lost as to what I might need to do...here is the code.  The line that produces the error is near the bottom and marked.  Any insights would be greatly appreciated.

Michael


Private Sub cmdPunch1_Click()

Dim intSubID, intCoderID, intRecordCount, intKeyCount As Integer
Dim strTable, strList, strWhere, strSQLcheck, strSQLKey As String

Dim varItems(), varCheckKeys(), varKey(), varCheckData() As Variant
Dim rstCheckKeys, rsttest, rstCheckData, rstAddKeys As ADODB.Recordset


    intSubID = Me!lstSubID.Column(0)
    intCoderID = Me!lstCoderID.Column(0)
    strTable = "ftbl" & Me!lstFirst.Column(0)
    strForm = "ffrm" & Me!lstFirst.Column(0)
       
           
'Debug.Print intSubID, intCoderID, strTable
   
'Step 1: determine if ID is the only primary key

  strSQLKey = "SELECT tblPrimaryKeyNames.KeyName" & vbCrLf
  strSQLKey = strSQLKey & "        FROM tblPrimaryKeyNames" & vbCrLf
  strSQLKey = strSQLKey & "       WHERE (((tblPrimaryKeyNames.TableName)=" & """" & strTable & """" & "))" & vbCrLf
  strSQLKey = strSQLKey & "    GROUP BY tblPrimaryKeyNames.KeyName" & vbCrLf
  strSQLKey = strSQLKey & "      HAVING (((tblPrimaryKeyNames.KeyName)<>""ID""));"

  Debug.Print strSQLKey
   
---------SIMILAR LINE OF CODE RUNS FINE ------
  Set rstAddKeys = CurrentProject.Connection.Execute(strSQLKey)
---------SIMILAR LINE OF CODE RUNS FINE

  varCheckKeys() = rstAddKeys.GetRows
  intRecordCount = UBound(varCheckKeys, 2)
  rstAddKeys.Close
 
 
  If intRecordCount > 0 Then
        'Step 2: If more than one primary key, then use inputbox to get values for them
                'add key names to array
        ReDim varKey(0, intRecordCount)
             
        For a = 0 To intRecordCount
            varKey(0, a) = inputbox(varCheckKeys(0, a), "Enter the value for:")
        Next
       
       
        'SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Relative, ftblDataEntryTest.Battery
        'FROM ftblDataEntryTest
        'WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Relative)="uncle")
        'AND ((ftblDataEntryTest.Battery)="first"));

       
        strList = strTable & ".ID, "
        strWhere = strTable & ".ID)=" & intSubID & ") AND (("
               
        For x = 0 To intRecordCount
            If IsNull(varCheckKeys(0, x)) = False Then
                strList = strList & strTable & "." & varCheckKeys(0, x) & ", "
                strWhere = strWhere & strTable & "." & varCheckKeys(0, x) & ")= " & varKey(0, x) & ") AND (("
            Else
            End If
        Next
        strList = Left$(strList, Len(strList) - 2)
        strWhere = Left$(strWhere, Len(strWhere) - 7)
       
       
  Else
        strList = strTable & ".ID"
        strWhere = strTable & ".ID)=" & intSubID & ")"
                     
  End If
 

'Step 3: Create StrSQL based on strList and strWhere key values

        strSQLcheck = "SELECT " & strList & " FROM " & strTable & vbCrLf
        strSQLcheck = strSQLcheck & "  WHERE ((" & strWhere & ";"
       
        Debug.Print strSQLcheck
 

'Step 4: Determine if a record for these key values already exists

------------ ERROR PRODUCED HERE ---------  
    Set rstCheckData = CurrentProject.Connection.Execute(strSQLcheck)
-------------ERROR PRODUCED HERE----------

    If rstCheckData.RecordCount > 1 Then
        MsgBox "Data for this subject already exists in this table.  Go to the Edit Data area instead"
    Else

'Step 5: If new, then open form and pass values
 
   
        varItems = adhPutItem(varItems, "SubID", intSubID)
        varItems = adhPutItem(varItems, "CoderID", intCoderID)
             
        DoCmd.OpenForm strForm, , , , , , OpenArgs:=varItems
    End If

   
End Sub
pansophyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

svenkarlsenCommented:
It's a bit complex, but it looks to me like you miss some closing right parenthesis for one of the possible outcomes of building StrWhere.

try running it to Immediate window and inspect the strSQLcheck instead of executing.
0
stevbeCommented:
do not use vbCrlf in your SQL strings

  strSQLKey = "SELECT tblPrimaryKeyNames.KeyName"
  strSQLKey = strSQLKey & " FROM tblPrimaryKeyNames" &
  strSQLKey = strSQLKey & " WHERE (((tblPrimaryKeyNames.TableName)=" & """" & strTable & """" & "))"
  strSQLKey = strSQLKey & " GROUP BY tblPrimaryKeyNames.KeyName"
  strSQLKey = strSQLKey & " HAVING (((tblPrimaryKeyNames.KeyName)<>""ID""));"


aside:

Dim intSubID, intCoderID, intRecordCount, intKeyCount As Integer

only intKeyCount get created as an integer all others will be variants, the same with your other declaration lines. In vba you need to declare the data type of each variable individually or else they will default to variant.

Steve
0
pansophyAuthor Commented:
svenkarlsen>  

This is the SQL statement copied directly from the immediate window (produced using the debug.print command)

SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Battery, ftblDataEntryTest.Relative
FROM ftblDataEntryTest
WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Battery)=1) AND ((ftblDataEntryTest.Relative)="uncle"));

The statement runs when I copy it into a SQL query window.  

Could the module be corrupted??
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

svenkarlsenCommented:
I aggree with Steve on the Dim. And it could be the source of problem here, - try making an explicit declaration like:

Dim rstCheckKeys As ADODB.Recordset, rsttest As ADODB.Recordset, rstCheckData As ADODB.Recordset, rstAddKeys As ADODB.Recordset

I also agree with Steve in principle on the vbCrLf, - but in this case I shouldn't think it would make any difference since it comes in front of keywords (don't do it in SQL Server pass-through though!).

Regards,
Sven
0
pansophyAuthor Commented:
I changed my declarations to:

Dim rstCheckKeys As ADODB.Recordset
Dim rsttest As ADODB.Recordset
Dim rstCheckData As ADODB.Recordset
Dim rstAddKeys As ADODB.Recordset

and removed the vbCrLf from all my SQL statements.  Sadly, I receive the same error.  

Another odd piece of information.  In this code I make two different SQL strings.  If I simply change

Set rstAddKeys = CurrentProject.Connection.Execute(strSQLCheck)

to

Set rstAddKeys = CurrentProject.Connection.Execute(strSQLKey)

Using the second SQL statement works just fine.  What about a SQL statement coudl cause the connection to fail??  

As I said, I copied the SQL string directly from the immediate window to a query and it ran perfectly.  So, I'm not even sure what could be wrong with a SQL that would allow it to run directly from a query window but cause a connection error in a module.

Thanks for any insights.
0
svenkarlsenCommented:
Try changing the two SQL Calls to:


rstAddKeys.Execute(strSQLKet), CurrentProject.Connection, adOpenDynamic, adLockOptimistic


rstAddKeys.Execute(strSQLCheck), CurrentProject.Connection, adOpenDynamic, adLockOptimistic
0
svenkarlsenCommented:
Just to be on the safe side: are you up to date with SP's ?

SP3: http://support.microsoft.com/default.aspx?scid=kb;EN-US;326585

And then I forgot, you might try closing rstAddKeys in between SQL calls:

set rstAddKeys =Nothing


Sven
0
svenkarlsenCommented:
Sorry, - i confused your code with another case, - disregard previous msg:
 
rstAddKeys.Execute(strSQLKey), CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rstAddKeys.Execute(strSQLCheck), CurrentProject.Connection, adOpenDynamic, adLockOptimistic

0
pansophyAuthor Commented:
rstAddKeys.Execute isn't a command, or at least it didn't let me run it as such.  I tried rstAddkeys.open with your suggestion and I got the same connection error.  

I'm really beginning to think the db is just corrupted...
0
pansophyAuthor Commented:
Okay, lets up this to 200 points.

I exported the three tables I needed for this code to a text file and copied the module to a text file as well to eliminate any corrupted elements from the data/code.

I imported the tables form the text files and copied the code into a module in a new database.  I got the same connection error.  

Better still, I simplified the code to this and still got the error:

Private Sub strProblem()

Dim strSQL As String
Dim rstCheckKeys As ADODB.Recordset

    strSQL = "SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Battery, ftblDataEntryTest.Relative FROM ftblDataEntryTest WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Battery)=4) AND ((ftblDataEntryTest.Relative)=""uncle""));"
   
Set rstCheckData = CurrentProject.Connection.Execute(strSQL)
 
End Sub

If I copy the Select statement into a query it retrieves records just as it should.  I am truly befuddled.

Thanks for keeping the suggestions coming.
0
pansophyAuthor Commented:
Well I found the solution.

Apparently, using the field name "relative" caused the problem.  Removing the field eliminated the error, so I changed the field name to 'family' and the code runs as it should.  

*sigh*
0
pansophyAuthor Commented:
svenkarlsen> Is there any way for me to give you the points for effort without misleading those scanning for help by accepting an incorrect solution as correct??  
0
svenkarlsenCommented:
Pan,
that's just one of those things ;-)

You're very kind, but as I did not provide a solution, I suggest you make a posting for point refund and question removal (please see the help for instructions).

Kind Regards,
Sven
0
jadedataMS Access Systems CreatorCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

PAQ - no points refunded

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jadedata
EE Cleanup Volunteer
0
SpazMODicCommented:
PAQed - no points refunded (of 200)

SpazMODic
EE Moderator
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.