VBScript not executing sql statment properly - sql

I write you this time because a VBScript that one of the application my company uses to retrieve information from an Oracle database does not seem to be working properly. Here are the facts:
There's part of the code that does the following:
sSql = "SELECT REQ_PAYMODE" & _
" FROM SYSADM.GBPRESTATIEGROEP" & _
" WHERE 1=1" & _
" AND SLEUTEL = " & sKeyPrestatiegroep
Set oRSGBPrest = connADO.execute(sSql)
If Not oRSGBPrest.EOF Then
sRequestPaymodeKey = oRSGBPrest("REQ_PAYMODE")
Else
//error handling
End If
Using a Statement Tracer for Oracle (www.aboves.com) I can capture that same statement with its corresponding value:
SELECT REQ_PAYMODE FROM
SYSADM.GBPRESTATIEGROEP WHERE 1=1 AND
SLEUTEL = 1572499
Now, the VBScript is supposed to take that value and execute another query:
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & sRequestPaymodeKey
Set oRSPaymodes = connADO.execute(sSql)
Right in this last line of code, the script throws an error that says:
ORA-00936: missing expression at line XXX --> Set oRSPaymodes = connADO.execute(sSql) <--
Which basically means that the query in (3) is not correct, which also means that for some reason sRequestPaymodeKey is empty. I cannot tell this for sure because this failing sql statement does not appear in the statement tracer, but that's the only explanation I could find. However, the worst part is that when running the query (2) on SQLDeveloper (that's where value sRequestPaymodeKey comes from) it shows a row with a value other than null or zero.
I can't think of anything else that might be happening here, maybe it's just a server thing... no idea.
Any suggestions from you guys? Any way I can actually debug a VBE file?
Your help is much appreciated!

You need to cast sRequestPaymodeKey as a vbLong which corresponds to sql's INT. I'm assuming PAM_KEY is an INT. A recordset will return a string value. So, your code would look like this:
If IsNumeric(sRequestPaymodeKey) Then
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & CLng(sRequestPaymodeKey)
Set oRSPaymodes = connADO.execute(sSql)
Else
'do error handling due to bad returned data(empty string?)
End If
Also, consider parameterizing your queries to prevent sql injection.

A few ideas to try:
Before Set oRSPaymodes = connADO.execute(sSql), put in a MsbBox and see what SQL is being executed. Is it valid? Will it run in a Oracle query analyzer(if there is one)?
Hard code a valid value in place of sRequestPaymodeKey. Does it work then?

Related

Syntax error in where clause in Access

The error I am getting is Syntax error in where clause in Access.
Here is the code:
SQL = "Select * FROM tblPermitAgencyInformation & WHERE [RecordID] = " & Me.AgencyInfoRecordID.Value
Set rs = db.OpenRecordset(SQL)
RecordID is an autonumber field and the AgencyInfoRecordID is an integer.
It looks like you misread the article you state. It appears to be attempting to format the adhoc query in the text variable.
Note: it says
strSQL = "SELECT wazzle FROM bamsploot" & vbCrLf & " WHERE plumsnooker = 0"
You need to make sure that you have the ampersands outside of the quotes, (they are used to append variables and strings together in this case)
Follow June7 advice and remove the ampersand there. It should help you get running.
Make your code this:
SQL = "Select * FROM tblPermitAgencyInformation WHERE [RecordID] = " & Me.AgencyInfoRecordID.Value
Hope that helps

Inserting Single/double type to DB using VBA in access

I need some help with an issue that is doing my head in.
I need to update a database in access and its been working fine operating with Long and Integers.
Look at this code.
sql = "UPDATE DBNAME SET Long_Field = " & Long_Variable & " WHERE ID = " & id
DoCmd.SetWarnings (False)
DoCmd.RunSQL sql
This code runs flawlessly, it takes a long variable and puts it into the correct field which is set as Long.
However, if I want to populate a single/double field (ive tried both)
sql = "UPDATE DBNAME SET Double_Field = " & double_Variable & " WHERE ID= " & id
DoCmd.SetWarnings (False)
DoCmd.RunSQL sql
I keep getting Run-Time error 3144: Syntax error in update statement.
I can literally just switch out the field name and the variable name and the code runs flawlessly, but as soon as i try to send a double value, for example (5,8), to a field in the table that is set to double, it gives me this error.
Anyone?
I assume that you want a dot as decimal separator in your string.
The conversion from double to string is done using the separator from the system locale settings so in your case a comma.
This means that
double_variable = 5.8
sql = "... " & double_variable & " ..."
will produce ... 5,8 ... in the sql variable.
The easiest way to fix that is to use
"..." & Replace(CStr(double_variable), ",", ".") & "..."
This will replace all , with .. I put the CStr there to make sure it gets converted to a string first. It will also work if the system locale changes since nothing will happen if there is no ,. The only caveat is that if for some reason the conversion inserts 1000s separators it will fail but that would only be relevant in other circumstances as I don't think CStr will ever do that.
The current answer is not the easiest, neither the simplest.
The universal method is to use Str as it always returns a dot as the decimal separator:
sql = "UPDATE DBNAME SET Double_Field = " & Str(double_Variable) & " WHERE ID = " & id & ""

Access 2010 VBA: SQL insert query is picking up 1 variable but not the other variable

OK usually I'm pretty good at googling around and using debug.print to isolate and solve the problem but this one is escaping me.
The purpose of this code is to create a new record in a table, using a form in which a person has selected a team member's name from a dropdown and a project phase from a dropdown and then input a number of hours into a textbox, then clicked a button that says "Add". There are a few if/thens involved but I'm leaving out the irrelevant parts (the code produces the same error in all cases.)
All of the code takes place inside one public function. All variables are Dim.
First it runs some code to find the value of "MyPersonID". (Complicated and not relevant as that works just fine).
Then it runs some code to find the value of "MyProjectPhaseID" which looks like this:
MyProjectPhaseID = [Forms]![HourValidationsFromTeam]![InputProjectPhase]
This variable populates correctly (as per Debug.Print)
Then it creates the INSERT SQL statement and runs it:
strAppendHourRecordSQL = "INSERT INTO PersonCommitmentsHours ( PersonNameLookup, ProjectPhase, WeekOfCommitment, DateValidated, HourCommitment, ValidationResult ) SELECT '" & (MyPersonID) & "' AS PersonNameLookup, '" & MyProjectPhaseID & "' AS ProjectPhase, [Forms]![HourValidationsFromTeam]![LastWeekDate] AS Week, Date$() AS TodaysDate, [Forms]![HourValidationsFromTeam]![InputSuppliedHours] AS Hours, " & Chr(34) & "More" & Chr(34) & " AS ValidationType;"
Debug.Print MyProjectPhaseID
Debug.Print strAppendHourRecordSQL
DoCmd.RunSQL strAppendHourRecordSQL
This is what Debug.Print returns:
2069
INSERT INTO PersonCommitmentsHours ( PersonNameLookup, ProjectPhase, WeekOfCommitment, DateValidated, HourCommitment, ValidationResult ) SELECT '260' AS PersonNameLookup, '' AS ProjectPhase, [Forms]![HourValidationsFromTeam]![LastWeekDate] AS Week, Date$() AS TodaysDate, [Forms]![HourValidationsFromTeam]![InputSuppliedHours] AS Hours, "More" AS ValidationType;
The query runs correctly and inserts a record with everything in the right place except it's missing the value where MyProjectPhaseID should go. It's just null. I thought maybe the variable was null, but Debug.Print returns the correct value. Even the debugger fills the value in when I hover over the SQL.
I tried different combinations of adding and removing parentheses and quotes around the variable in the SQL but they have no effect.
Please help!
I figured out the problem. The problem is that you cannot define the SQL before the variables have been populated. I thought you could define the SQL and then re-use it depending on where you get your variables from. But no. That's why it had the right value for the variable, but it couldn't put them together. I didn't make it clear from the way I wrote the question that this could be a suspect, i'm sorry about that.
So in order to not try to pre-define SQL for variables that don't exist yet, I isolated the part of the SQL that won't change and define that first as strBoilerplateSQL.
Then do the IF statement for the stuff that could change, then define the part of the SQL statement that depends on that change, then concat the 2 sql statements together. Then it runs the completed SQL statement.
strBoilerplateSQL = "INSERT INTO PersonCommitmentsHours ( PersonNameLookup, WeekOfCommitment, DateValidated, HourCommitment, ValidationResult, ProjectPhaseLookup ) SELECT " & (MyPersonID) & " AS PersonNameLookup, [Forms]![HourValidationsFromTeam]![LastWeekDate] AS Week, Date$() AS TodaysDate, [Forms]![HourValidationsFromTeam]![InputSuppliedHours] AS Hours, " & Chr(34) & "More" & Chr(34) & " AS ValidationType, "
'Check to see if this is going in to an existing project or should we create a new project first
If (IsNull([Forms]![HourValidationsFromTeam]![InputNewProject].Value)) Then
'If the Input New Project text box is null, assemble the SQL and run it
MyProjectPhaseID = [Forms]![HourValidationsFromTeam]![InputProjectPhase].Value
strMyProjectPhaseSQL = "" & (MyProjectPhaseID) & " AS ProjectPhase;"
strReadySQL = (strBoilerplateSQL) & (strMyProjectPhaseSQL)
DoCmd.RunSQL strReadySQL
Else
'Some other stuff happens here
MyProjectPhaseID = GetPhaseID![TheProjectPhase]
'Now that we have the new project phase ID we can run the SQL from above (oh hey remember that?)
strMyProjectPhaseSQL = "" & (MyProjectPhaseID) & " AS ProjectPhaseLookup;"
strReadySQL = (strBoilerplateSQL) & (strMyProjectPhaseSQL)
DoCmd.RunSQL strReadySQL
End If

SQL Access VBA UPDATE table with another table? Too Few Parameters

I am looking to update one of my tables with another table depending on a field condition. I am wondering what the correct way to do this is. I tried to do UPDATE statements with the 2 tables, but everytime it came out with this error: Too few Parameters, Expected 2
My goal:
If SOURCING field = O, I want Zip Code to be Origin Postal Code
If SOURCING field = D, I want Zip Code to be Dest Postal Code
So as of right now, I am simply doing a LEFT JOIN with a condition. Is this the best way to do it? Or should I have done this with the original INSERT statement somehow?
CurrentDb.Execute "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Origin Postal Code]" & _
" WHERE tblImport.[Sourcing] = O;"
CurrentDb.Execute "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Dest Postal Code]" & _
" WHERE tblImport.[Sourcing] = D;"
I have tried changing the WHERE statement since I am not sure if it should be in quotes, single quotes, not in quotes, etc... but I have come up empty there. Everything else looks correct to me.
Here's what I do, you might find this helpful; Set a variable equal to your SQL string, then CurrentDB.Execute the variable. Why is this helpful? Because you can break the code after the variable is set, and then copy the SQL into a new query and see what it's complaining about. :o)
Dim tmpUpdate as string
tmpUpdate = "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Origin Postal Code]" & _
" WHERE tblImport.[Sourcing] = O;"
CurrentDB.Execute tmpUpdate
Set a breakpoint on the "tmpUpdate =" line, and then run the code. When it hits the breakpoint, press F8 to step to the next line. In the Immediate window, type "?tmpUpdate" (without the quotes) and see what it thinks the variable is equal to. Then, go to the database, create a new query and go to the SQL of the query. Copy and paste the SQL from the Immediate window and try running the query. If it pukes, go to the Design view and see if you can see anything that doesn't look right.

Classic ASP bizarre SQL error

I am connecting to a Access DB, with following Conn String
Conn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=\\server\share\Data\PFWTRAN.MDB"
The following SQL works fine;
SQLIn = "SELECT Date, Time " & _
"FROM Transactions " & _
"WHERE TokenNumber = " & TokenNo & " " & _
"AND Date >= " & FromDateG & " " & _
"AND Direction = -1 " & _
"ORDER BY Date, TransactionNumber;"
However, I want rows where Transactions.Exception = 0, yet when I add this AND condition, the script fails when the RS is opened;
error '80004005' /path/.../.../...asp, line 97
If I remove the AND condition, it works again.
Even If I try and put 'Exception' in the SELECT section, it won't run and gives me that error.
Why would the inclusion of one field cause such an error? I read the error is due to permissions, but my permissions are fine as the SQL works without this one field in it.
Any clues?
It is a very old Access 95 database (or even earlier), perhaps I need to change connection provided?
"However, I want rows where Transaction.Exception = 0, yet when I add this AND condition, the script fails when the RS is opened"
But Transaction.Exception refers to a different table than the one your query uses.
FROM Transactions
Date, Time, and Exception are Problem names and reserved words in Access. Enclose those names in square brackets, or prefix them with the table name/alias.
Consider switching your approach to use a parameter query ... and feed it TokenNo and FromDateG values as parameters, rather than building their values into the SELECT statement.