SQL UPDATE based on condition - updates

We need to update a table with the users id (NBK). The table with NBK also has the user status (0 - 1) and only one user will have 1 at a time. The challenage is to #1 capture the active user #2 update the other table with the user NBK. I hope the code below just has a simple syntex error that I cannot find?
Dim nb As String
Dim NBK As String
nb = [Employees]![NBK] & "' WHERE "
nb = nb & " " & [Employees]![Status] = '1'
NBK = " Update tbl_DateTracking SET NBK = "
NBK = NBK & "'" & nb & "' WHERE "
NBK = NBK & "CaseId = '" & CaseId & "' AND OCC_Scenario = '" & OCC_Scenario & "' ;"
DoCmd.RunSQL nb
DoCmd.RunSQL NBK

Several pointers of note here:
You should use parameterized queries instead of string concatenation. This prevents/contains SQL injections and other issues regarding malformed input.
Ideally, you should normalize the database so that "active user" is not a field on the user table. What happens when there are two users set as "active" in the database?
With this given schema however, you're going to want to use a sub-select query. Ex:
UPDATE tbl_DateTracking SET NBK=(SELECT NBK FROM Employees WHERE Status=1 LIMIT 1) WHERE CaseID=? AND OOC_Scenario=? and then pass in CaseId and OOC_Scenario as the parameters.
Note, I'm not familiar with VB or how it interacts with SQL; The above is just an example, you'll have to apply it to your application and alter it to make it work. The way you're building and running the nested queries also looks like it won't work, since your first query doesn't contain a command (You probably want SELECT, I think. Does VB do that automatically with []![] syntax?), and when you nest it inside the second query, it's not surrounded with (). Running the first query by itself also has no effect if you're including it as a sub-query in the second one.

Related

Look for duplicate records before adding a record

I clipped this from another post, since it is similar to what I need. Instead of using me.ID, etc, I need to reference a field in another table, specifically [Formdate] in a table named Brief Sheet.
I tried many variations, such as table "Brief Sheet".Formdate but no luck
What would be the proper syntax?
rst.FindFirst "[ID] <> " & Me.ID & _
" AND [TitleText] = '" & Me.TitleText & _
"' AND [UnitCode] = " & Me.UnitCode & _
" AND [AcademicYear] = " & Me.AcademicYear & _
" AND [Titleofchapterjournalarticle] = '" & Me.Titleofchapterjournalarticle & "'"
Use Dlookup. In the snippet you posted, the coder has already instantiated a recordset and is using recordset methods to find a record within it. What you said you want to do is actually a little simpler.
Below is a test procedure to illustrate getting your date value from your table.
You didn't clarify what criteria you would use to select the proper FormDate from the table "Brief Sheet", so I included "ID=3", which will select the FormDate record, whose ID=3. Adjust that as necessary.
Also, if your table name really is "Brief Sheet", and you have the ability to rename it, I highly recommend establishing some naming convention rules for your tables, first not having any spaces. Even Brief_Sheet would make your life easier down the road.
Public Sub Test1()
'dimension a variable to hold the date value
Dim datFormDate As Date
'fill the variable with the value you need to reference
datFormDate = DLookup("FormDate", "Brief Sheet", "ID = 3")
'Print the value to the "immediate" pane (just for testing)
Debug.Print datFormDate
'If you're running this code from within your form module, you can assign
'the value in your variable to a field in your table as such:
me.DateFieldtxtbx = datFormDate
End Sub

How to get an Access Userform to update an existing record

I'm trying to get an access userform button to run an update query.
The parameters I have are:
Invoice number (should update Current ICB.Invoice number)
Material Code (should update Current ICB.Material Code)
Amount USD (Should update current ICB.Amount USD)
Username (Should update current ICB.Owner)
Vendor Code (Should update current ICB.Vendor code)
Record Number (Should = current ICB.ID)
I want to use a button on the form to check for a record that has the same record number and update the fields listed above with the values entered into the userform. I would use an update query but writing SQL into VBA is not my strong point. Any ideas?
In the OnClick event of the button, do something like this:
Dim db as Database
Dim rec as Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("Select * from MyTable where RecordNumber = " & ICB.ID & "")
rec.Edit
rec("InvoiceNumber") = ICB.Invoice_number
rec("MaterialCode") = ICB.Material_Code
etc...
rec.update
rec.close
Use your actual table and field names, but that's the general idea.
If you absolutely insist on using a query, then you need to write the SQL in code in a similar way and use DoCmd.RunSQL. Something like this:
txtSQL = "UPDATE MyTable SET InvoiceNumber = " & ICB.Invoice_number & ", " & _
" MaterialCode = " & ICB.Material_Code & "" & _
etc...
" WHERE RecordNumber = " & ICB.ID & ""
DoCmd.RunSQL txtSQL
This assumes you're only using integers. If you're storing the data as text, it needs to be surrounded by single quotes.
" MaterialCode = '" & ICB.Material_Code & "'" & _

How to search and find and filter in Access vba

In my Access database, I'm trying to perform a search and find routine which is quite complicated. Basically, I have 4 criteria to look for in these four tables: Date, Service, Code and Function.
With this information I go into a table, and search in a field and for one criteria. After I've found the rows which correspond to one of the 4 criteria, I save the value of the neighboring field for all the rows which matched correctly. After this, I wanted to save the values of all the neighboring fields as an array. Then repeating these steps, I was going to save all 4 searches as 4 individual arrays.
The relationships of my tables are as follows:
I receive a "Demande" which is a request, and in that request are the four criteria: Date, Service, Code and Function.
In the table "Services_YES" I look for the Service that corresponds to the demand.
In the table "Pool_Personnel" I look for the Fonction that corresponds to the demand.
In the table "Days_Available" I look for both the Date and the Code (called Code_Horaire) which corresponds to the demand.
From there, I was hoping to record each Code_Personal for all of the results found, and then find which Code_Personal's matched in all of the 3 tables.
So My question:
How I can do a search and find function which creates an array of for all of the Code's which correspond to the criteria rows?
I have created psuedo code to help explain, and incase someone can translate this into real VBA:
While demandeTable.functionField.Value = poolpersonnelTable.Fonction1Field.Value
get all poolpersonnelTable.codepersonalField.Value for all rows that match
save fonctionArray = codepersonalField.Values
Loop
I'm very stuck on how to complete this 'filtering', and would strongly appreciate all help.
Using VBA is not the answer.
I ended up creating a Query, and using user-inputed text to fill in the variable parts of the query:
comboService = Chr(34) & Me.Combo8.Value & Chr(34)
txtDate = Chr(34) & Me.Text15.Value & Chr(34)
comboCodeHoraire = Chr(34) & Me.Combo17.Value & Chr(34)
"SELECT tblPoolPersonnel.LName, tblPoolPersonnel.FName, tblPoolPersonnel.[Tel Natel], tblPoolPersonnel.[Tel Home], tblPoolPersonnel.Email" & vbCrLf
"FROM ((tblPoolPersonnel INNER JOIN tblFonction ON tblPoolPersonnel.Code_Personal = tblFonction.Code_Personel) INNER JOIN tblDayAvailable ON tblPoolPersonnel.Code_Personal = tblDayAvailable.Code_Personal) INNER JOIN tblServiceYES ON tblPoolPersonnel.Code_Personal = tblServiceYES.Code_Personal" & vbCrLf
"WHERE (((tblServiceYES.Service)=" & comboService & ") AND " + _
"((tblDayAvailable.Availability)=True) AND " + _
"((tblDayAvailable.Date)=" & txtDate & ") AND " + _
"((tblDayAvailable.CodeHoraire1)=" & comboCodeHoraire & "))"

ASP issue in retrieving datas

set rs6= objconn.execute("select TotalDays from newbank where " & _
"newbank.empid= '" & session("EmpID") & "' and newbank.LeaveType = 23")
Here 23 is the value in the Field named LeaveType, but TotalDays are not being retrieved. Can you help to solve this?
Thank You
save sql and variables to a string first
EmpID = session("EmpID")
sql = "select TotalDays from newbank where empid= '" & EmpID & "' and LeaveType = 23"
log(EmpID )
log(sql)
Must EmpID be a string ?
log is your debugging or logging routine you unbdoubtly have..
session and request variables are best placed in a stringvariable first so you're sure of the type and can inspect the contents
like suggested above test the contents op the sql var againt your database, if it works there perhaps something is wrong with your connectionsetup

MS-Access 2003 - Expression in a Text Box on a form

just wondering when using an expression on a form in a text box, to return a value from a table, can the expression have multiple tables in the expression to return the value?
the tables are linked and I can return the value in a query, so I figured that Access would be able to do it with this method as well????
=DSum("[tblMain]![Revenue]","tblMain","[tblMain]![Quarter]=3 AND [tblMain]![Region]='NorthEast'" AND [tblOffice]![Location]='NewYork'")
this is the expression that I entered into my text box, without the reference to the 2nd table it works fine, but once I had it, I get the flickering error message in the text box (just as on a report)......
I know this method is probably used more in reports than forms, but I am novice, and trying to come up with a dashboard solution that returns lots of facts quickly per department. I am using this in the "Control Source" field of the data tab of the properties window, not VB. Mainly because I do not know how to get it to work with VB.
Thanks for the help as always!
As far as I know, you cannot refer to more than one table or query in a domain aggregate function. As grazird says, how are these tables related? Let us say it is on tblMain ID, you can build a query called, say, qryMainOffice, the SQL (SQL View, Query Design window) would look something like:
SELECT [tblMain].[Revenue],[tblMain]![Quarter],[tblMain]![Region],
[tblOffice]![Location]
FROM tblMain
INNER JOIN tblOffice
ON tblMain.ID = tblOffice.MainID
DSum would then be (remove line break):
=NZ(DSum("[Revenue]","qryMainOffice",
"[Quarter]=3 AND [Region]='NorthEast' AND [Location]='NewYork'"),"Not found")
You could also use a recordset or query in VBA to return the value.
EDIT re COMMENT
To use the above in VBA, you either need to add parameters or use a string:
''Reference: Microsoft DAO 3.x Object Library
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db= CurrentDB
strSQL = "SELECT Sum(t.[Revenue]) As TotalNY" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "AND o.[Location]='NewYork' " _
'' I have use aliases for simplicity, t-tblMain, o-tblOffice
'' If you wish to reference a control, use the value, like so:
'' & " AND [Location]='" & Me.txtCity & "'"
'' Dates should be formated to year, month, day
'' For joins, see http://www.devshed.com/c/a/MySQL/Understanding-SQL-Joins/
Set rs = db.OpenRecordset strSQL
If Not rs.EOF Then
Me.txtAnswer = rs!TotNY
Else
Me.txtAnswer = "N/A"
End If
You can also use different queries to return several results that can be shown with a list box or a subform:
strSQL = "SELECT TOP 5 o.[Location]," _
& "Sum(t.[Revenue]) AS TotRevenue" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "GROUP BY o.[Location]"
The above would return revenue for quarter 3 for all locations in NorthEast region. If you want the top values of each group, you are looking at a more complicated query, which I will leave for now.
How are these tables related? Can you describe the relationship and any primary/foreign keys?
Also, referencing the table name is not necessary in the first parameter of this function (since it is already taken care of in the second one).
For example, your code could be:
=DSum("Revenue","tblMain","Quarter=3 AND Region='NorthEast'" AND [tblOffice]![Location]='NewYork'")
Just trying to save you some keystrokes and increase its readability. :)