Use a VB variable in a SQL statement - sql

I'm trying to create a sql statement but I require the use of a VB variable. The problem is, I keep getting an error about too few parameters when I try to just put the variable in. Is there some sort of format I need to use in order to add a VB variable into a SQL statement?
Set rs = CurrentDb.OpenRecordset("SELECT StartTime " & _
"FROM tblLunchTime " & _
"WHERE TimeID = (SELECT max(TimeID-count) FROM tblLunchTime);")
The variable in this situation is 'count'.

concatenate the variable like so:
Set rs = CurrentDb.OpenRecordset("SELECT StartTime " & _
"FROM tblLunchTime " & _
"WHERE TimeID = (SELECT max(TimeID-" & count & ") FROM tblLunchTime);")

Well... using non-parameterized sql like you want to is usually a very bad idea. There are many articles on how to parameterize a sql query or use stored procs for VB (6 and .NET).

You need to concatenate it:
Set rs = CurrentDb.OpenRecordset("SELECT StartTime " & _
"FROM tblLunchTime " & _
"WHERE TimeID = (SELECT max(TimeID-" & count & ") FROM tblLunchTime);")

Related

using what I think is a variable in a SQL statement

I am very new to SQL and think I have a simple problem but was unable to figure it out from other posts. I have the following code:
INSERT INTO tblShortScores ( TradeNum, FilterNum, Rank, ScoreNum )
SELECT [Forms]![frmOpenTrades]![TradeNum] AS TradeNum, tblFilters.FilterNum, tblFilters.SBBExh AS Rank, tblFilters.SBBExh AS Score
FROM tblFilters
WHERE (((tblFilters.SBBExh) Is Not Null));
but instead of using the literal "SBBExh" in tblFilters.SBBExh, I want to do something like
tblFilters.("S" & [Forms]![frmOpenTrades]![Strategy])
where something like
[Forms]![frmOpenTrades]![Strategy] contains the value "BBExh".
It's in MS Access and I seem unable to find a syntax that works
any help is appreciated
Can't dynamically build field name in query object. Use VBA to construct and execute action SQL, like:
strField = "S" & Me.Strategy
CurrentDb.Execute "INSERT INTO tblShortScores (TradeNum, FilterNum, ScoreNum) " & _
"SELECT " & Me.TradeNum & " AS TradeNum, FilterNum, " & strField & " " & _
"FROM tblFilters WHERE " & strField & " Is Not Null;"
Assumes TradeNum is number type - if it is text, use apostrophe delimiters:
SELECT '" & Me.TradeNum & "' AS .
If SQL injection is a concern review, How do I use parameters in VBA in the different contexts in Microsoft Access?

Finding/Marking Duplicate Values using SQL

I am trying to update a column in my table to specify if the record is a duplicate or not. To do this I added a field called 'DuplicateRecord'.
I can't use the query wizard in access as the duplicate option in this only allows for 10 fields to be checked as a duplicate and my table has more than 10 fields.
The below code works for me:
Call Module1.RunSQL("UPDATE myTable " & _
"SET myTable.DuplicateRecord = TRUE " & _
"WHERE myTable.[CompanyID] IN (" & _
"SELECT * FROM " & _
"(SELECT myTable.[CompanyID] " & _
"FROM myTable " & _
"GROUP BY myTable.[CompanyID] " & _
"HAVING COUNT(*) > 1 ) T1 ) ")
However this code just runs off one field and I need it to run off all fields in the table (there are about 15 fields).
As a test I tried using two fields to see if I could get this working using the following:
Call Module1.RunSQL("UPDATE myTable " & _
"SET myTable.DuplicateRecord = TRUE " & _
"WHERE myTable.[CompanyID] AND myTable.[Product] IN (" & _
"SELECT * FROM " & _
"(SELECT myTable.[CompanyID], myTable.[Product], COUNT(*) " & _
"FROM myTable " & _
"GROUP BY myTable.[CompanyID], myTable.[Product] " & _
"HAVING COUNT(*) > 1 ) T1 ) ")
However I get an error message saying "Run-time error '3306' You have written a subquery that can return more than one field without using the EXISTS reserved word in the main query's FROM clause. Revise the SELECT statement of the subquery to request only one field."
I've tried googling the error but I can't seem to solve it as I don't fully understand it.
Does anyone know how I can apply the logic of testing for duplicates? Is there an easier way to do this then how I am currently trying? I will need to do this for the full record (15 fields), so I am a bit conscious that the way I am currently attempting this might not be the best fit.

VBA Query returning nulls

Using the query builder in Access I am able to find the total, but I need to find the total using the vba code builder. The code given here gives me a null value.
Dim rst As DAO.Recordset
Dim dbs As Database
Dim strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT Sum(GiftRcvd.Rcvdamount) AS SumOfRcvdamount FROM OurEvents INNER JOIN GiftRcvd ON OurEvents.EventName = GiftRcvd.EventName " & _
"WHERE ((([OurEvents].[EventDate])>" & Me.DateFrom.Value & " And ([OurEvents]![EventDate])< " & Me.DateTo.Value & "));"
Set rst = dbs.OpenRecordset(strSQL)
SumOfRcvdamount = rst![SumOfRcvdamount]
MsgBox SumOfRcvdamount
It's likely that your query is returning an empty recordset. Assuming you have data, this most likely means that your HAVING clause is filtering out the records you want.
As I remember, date literals in Access have to be in the format #1/30/2019#: a clause in the form [EventDate] > 1/30/2019 will not evaluate the way you want.
So try bracketing those date parameters with #:
[OurEvents].[EventDate])> "#" & Me.DateFrom.Value & "#"
Strictly speaking, you should avoid assembling queries from strings (due to the possibility of SQL Injection attacks): you should instead parameterize them and pass parameter values. BUT, that's harder to do in Access than in other forms of SQL.
You have to format your date values to valid string expressions:
"WHERE ((([OurEvents].[EventDate])> #" & Format(Me.DateFrom.Value, "yyyy\/mm\/dd") & "# And ([OurEvents]![EventDate])< #" & Format(Me.DateTo.Value, "yyyy\/mm\/dd") & "#));"

Syntax error in SQL update

I am new to both MS Access and SQL. Now I am trying to create an inventory database for our company in Ms Access. I try to extract data from the reception form to update the inventory balance. But I met a syntax error message when I executed a SQL update statement. This is weird for me because I used the same statements that successfully running in other tables. The only difference is my former successful update working by direct text replacement and my error occurring update is working in a numeric object.
Please help me to check where I am wrong.
This is my code:
Private Sub Command96_Click()
CurrentDb.Execute "UPDATE tbl_Current_Stock" & _
"SET Stock_Level= Stock_Level + " & Me!txtOrderQty & "" & _
"Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
End Sub
Thanks!
You need to add spaces before SET and Where. Otherwise, your command will look something like UPDATE tbl_Current_stockSET Stock_Level= Stock_Level + 3Where.....
Private Sub Command96_Click()
CurrentDb.Execute "UPDATE tbl_Current_Stock" & " " & _
"SET Stock_Level= Stock_Level + " & Me!txtOrderQty & " " & _
"Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
End Sub
You might also need to wrap the Raw_Material column in quotes if it is not numeric.
check your sentence correctly. there is no technical error. there are some space missing in you query.
just add white space before "SET" and "where" words.
CurrentDb.Execute "UPDATE tbl_Current_Stock" & _
" SET Stock_Level= Stock_Level + " & Me!txtOrderQty & "" & _
" Where tbl_Current_Stock.Raw_Material= " & Me!cboPurchase.Column(1) & ""
Friend, follow some tips to generate your updade correctly:
Check the spaces after concatenating your query
Be careful not to generate queries with keywords stuck together
UPDATE tableTestSET nome = 'My Name' WHERE active IS NOT NULL (wrong)
UPDATE tableTest SET name = 'My Name' WHERE active IS NOT NULL
Do not forget to use quotation marks when using strings
UPDATE tableTest SET name = My Name WHERE active IS NOT NULL (wrong)
UPDATE tableTest SET name = 'My Name' WHERE active IS NOT NULL
I hope it helps...
Good Luck!

SQL ORDER BY on Update- update last record with condition

I am trying to update the last record of table Log (the field with the latest TimeAccessed) given that TimeExited is null, and the computername is the same as the "cm" parameter. I have this but get error, "missing semicolon at end of sql statement"
what is wrong??
dbs.Execute "UPDATE Log " _
& "SET TimeExited = " & Format(CloseTime, "\#hh:mm:ss AMPM\#") _
& " WHERE TimeExited is NULL AND ComputerName = '" & cm & "'" _
& " ORDER BY TimeAccessed DESC" _
& " LIMIT 1; "
nothing wrong with first 2 lines, work perfectly fine, it's the last two that give problems
Access SQL doesn't use LIMIT n it uses TOP n, and as mentioned in the other question cited in the comments to your question, you aren't allowed to use TOP in the way you've described. Instead, you'll need to do something along these lines:
UPDATE Log
SET TimeExited = CloseTime
WHERE TimeExited IS NULL
AND ComputerName='r2d2'
AND TimeAccessed IN
(
SELECT TOP 1 TimeAccessed
FROM Log
WHERE TimeExited IS NULL
AND ComputerName='r2d2'
ORDER BY TimeAccessed DESC
)