parameterized query not working in VB - sql

statement = "SELECT OrderID, (SELECT VendName FROM Vendors WHERE Vendors.VendorID = Orders.VendorID) " &
",OrderDt, RcvdDt, OrderTotal " &
"FROM Orders " &
"WHERE VendName=? " &
"ORDER BY OrderDt DESC"
Dim cmd As New OleDbCommand(statement, connection)
cmd.Parameters.AddWithValue("VendName", txtVendorFilter.Text)
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.Default)
I was trying to do this before by simply concatenating the textbox value right into the SQL and I was getting a "No values given for required parameters", and read that that I should use parameterized queries instead. So I tried this and it doesn't give me any errors, but the reader never has anything in it. I've never used parameterized queries before, so I'm a bit lost as to why this isn't working.
Edit:
I've changed the above code to account for OLEDB from what I briefly read on how it should work, and it's giving me the "no values given for required parameters" again.

One problem is here:
"WHERE VendName='#x' " &
Drop the ' marks - the parameterization will take care of this for you:
"WHERE VendName= #x " &
Using the ' in the query means that '#x' is treated as a string type, not a parameter name.
Additionally, since you are using OleDb, names parameters are not supported. You need to use ? to signify a parameter in the query:
"WHERE VendName= ? " &

Related

Run one MS Access SQL script on a particular Table chosen by user

I have a MS Access 2016 database (*.accdb) with 20+ Tables. Fields in each of them vary slightly from Table to Table. I've no VBA experience, so I'm sticking only to the SQL query below (redacted).
SQL script
myvar below is the parameter I'd like to be prompted when the script is run so that I enter the Table I want the changes applied to.
PARAMETERS
[myvar] TableID;
UPDATE
[myvar]
INNER JOIN
Excel_Data ON [myvar].[Part Number] = Excel_Data.[Part Number]
SET
[myvar].[Value] = '?',
[myvar].Description = Excel_Data.Description,
[myvar].[Ref] = '?'
.
.
.
WHERE
[myvar].Description Is Null;
Output
Error message:
Too few parameters. Expected 0.
What I need
I prefer a solution for above in a SQL script form as above, not involving VBA, preferably. I'd like to enter the Table name when prompted so the script knows which table to UPDATE. FYI: The PARAMETERS work when it is not a Table as I've shown in my script above.
Help/advise is highly appreciated.
EDIT 1
Since it seems not possible to use parameters as Table names, could you suggest a VBA solution? A sample code, perhaps?
As said in the comments, you can't really solve this without VBA.
You can store your SQL query in a string, and use a placeholder to indicate the tablename. Then get the tablename using an inputbox and replace the placeholder with the tablename.
Dim sqlString As String
sqlString = "UPDATE [%Placeholder%] " & vbCrLf & _
"INNER JOIN Excel_Data ON [%Placeholder%].[Part Number] = Excel_Data.[Part Number] " & vbCrLf & _
"SET [%Placeholder%].[Value] = '?', " & vbCrLf & _
...
"WHERE [%Placeholder%].Description Is Null;"
sqlString = Replace(sqlString, "%PlaceHolder%", InputBox("Enter a tablename"))
CurrentDb.Execute sqlString
In a more mature solution, I'd create a form with a combobox containing all available table names, and add a function to sanitize tablenames (replace "]" with "]]")

No value given for one or more required parameters visual basic error

This error is appearing in following line of the vb code
rs.Open "select * From Reservation where [table_number]=tablenumber.text and booking_date=bookingdate.Text", cn, adOpenStatic, adLockPessimistic
It's a problem with your SQL query. The reason for the message is that the SQL parser can't identify a token in your SQL query and interprets it as a parameter for which you need to provide a value.
So, you either mistyped some of your field or table names, or you created your SQL the wrong way. I suppose the latter and it should read
rs.Open "select * From Reservation where [table_number] = " & tablenumber.text & " and booking_date=" & bookingdate.Text, cn, adOpenStatic, adLockPessimistic
because tablenumber and bookingdate are very likely form controls.
The above query won't work out of the box as you need to use the correct data types for the SQL query which I cannot infer based on your sparse information.
If you are INSERTing values in TABLE - dont miss enclosing it in single quotes, like
' " & text1.text & " '
example:
INSERT into [TABLE NAME]([Purchase Order Status]) values(' " & text1.text & " ')
I would suggest adding () around the selection criteria:
rs.Open "select * From Reservation where ( [table_number]=tablenumber.text and booking_date=bookingdate.Text )"

Vba requery parameter syntax

I need to set the parameter for a requery command, but I canĀ“t find the correct syntax.
tbTreinamentosConc.Requery Profissional = prof
tbTreinamentosConc refers to table Trn_Done, which has the column Profissional, among the others and prof is the parameter I want to be used when searching in the table Trn_Done, in the field Profissional.
What is the correct way to get it working?
Thanks in advance!
A requery will simply update the information in a given object, you can't pass arguments to it. You can however write an SQL statement to query for something specific...
Dim strSQL As String
strSQL = "SELECT * " & _
"FROM tbTreinamentosConc "
"WHERE Profissional ='" & txtInput & ";"
DoCmd.RunSQL strSQL
txtInput will be a text box on your field that you can enter the 'prof' parameter into; This should work.

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.

VBScript not executing sql statment properly

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?