SQL Query to set date activated for single row - sql

I have a registration form for users to submit and then when they click the activation link in their email, it activates their account (AccountActivated = true). This works fine, however, I also have a column called DateActivated set to smallinttime as the data type. I'm trying to find an SQL query that records the date that the account was activated.
This is the query I use to activate the account, so I'm guessing I need something similar to this:
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE
UserId=#UserId AND UMaryEmail=#txtEmailAddress"
So maybe something like this?
Dim sqlQuery2 As String = "UPDATE RegisteredUsers SET DateActivated=?? WHERE
UserId=#UserId AND UMaryEmail=#txtEmailAddress"
If someone could weigh in on this and let me know what the command is to set current date to the field, I'd greatly appreciate it.

You can do it all in the same query:
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1,DateActivated=GetDate() WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"

Related

Run SQL Update Query in MS Access VBA

I am trying to run this code to fire an update query from VBA. Access is giving me a syntax error. I suspect this has to do with the fact that I'm trying to run an update query using an INNER JOIN with a form. Is what I'm trying to do at all possible?
Private Sub Btn_Edit_Data_Click()
Dim db As DAO.Database
Dim UpdateQdf As DAO.QueryDef
Dim UpdateSQL As String
Set db = CurrentDb()
Set UpdateQdf = db.QueryDefs("Qry_Update_Counterparty_Data")
UpdateSQL = "UPDATE Repository_Redux INNER JOIN [Forms]![Frm_Reject_Button] ON Repository_Redux.[Counterparty ID] = [Forms]![Frm_Reject_Button]![Txt_CP_ID] " & _
"SET Repository_Redux.[Counterparty Name] = [Forms]![Frm_Reject_Button]![Txt_CP_Name_Edit]"
UpdateQdf.SQL = UpdateSQL
DoCmd.OpenQuery "Qry_Update_Counterparty_Data"
Set db = Nothing
Set qdf = Nothing
End Sub
I solved it this way, thanks everyone:
UpdateSQL = "UPDATE Repository_Redux SET Repository_Redux.[Counterparty Name] = [Forms]![Frm_Reject_Button]![Txt_CP_Name_Edit] WHERE Repository_Redux.[Counterparty ID] = [Forms]![Frm_Reject_Button]![Txt_CP_ID]"
Just a suggestion, I've not tried this...
On your form you have have an event handler that stores in a global variable (yes, I know that's dodgy) the values from your form that you intend to use in the query. Then you can define a function that reads the global variable. Then you can use the function in the SQL query.
Let us know how you get on.
Googling suggests other have tried this
Global Variable as query parameter - PC Review
How to put global variable name in query
Anybody else got a better "global state machine" to bridge the form to the SQL?
No, you can never join a form in a query (or SELECT FROM a form, for that matter). You can only join in tables or other queries.
You can, however, try to join in a forms record source.

SQL Select statement suddenly retrieving wrong value only when selecting form another query

I have a order creation form in an Access database where the user selects a product and VBA code is triggered with SQL select statement to retrieve the current availability of that product. This is how it's set up:
I have a Packages table where products batches are added to inventory.
I have an OrderDetail table where items from product batches are allocated to orders.
I have a InventoryPrep query with a the total packaged per batch and field that sums the number of allocated products per batch from the OrderDetail table.
Then I have an Inventory query that that has a calculated field that takes the TotalPackaged field from the InventoryPrep query and subtracts the TotalAllocated field from the InventoryPrep query.
Here is the VBA code in my form, triggered by an update to the [Batch] combo box:
Dim VBatch As String
VBatch = Me.Batch.Value
Dim VAvail As Double
Dim mySQL As String
Dim conn1 As ADODB.Connection
Set conn1 = CurrentProject.Connection
Dim rs1 As New ADODB.Recordset
rs1.ActiveConnection = conn1
mySQL = "SELECT Available FROM Inventory WHERE BatchID = " & "'" & VBatch & "'"
rs1.Open mySQL
rs1.MoveFirst
VAvail = rs1.Fields("Available").Value
Forms!ChangeOrders.ChangeOrderSubform.Form.Availability.Value = VAvail
rs1.Close
conn1.Close
Set rs1 = Nothing
Set conn1 = Nothing
This has been working just fine for weeks, retreiving the correct available amount as packaged items are added to the Packages table and orders are being added in the OrderDetail table. Yesterday it started returning the Packaged field from the InventoryPrep query instead.
I tried a bunch of things and then created a table from the query and used the SELECT statement to look it up in the table. That worked. There is something about my query set up that has caused it to stop recognizing my calculated field. I need help!
This is my first time posting and I hope this is enough information. I'm pretty new to Access and VBA but I've learned a lot from reading in this forum. I hope someone can help or let me know what other information could shed light on the problem.
To read a single value from a table or query, your code is a bit over the top.
For this scenario, Access has the DLookup function.
VAvail = DLookup("Available", "Inventory", "BatchID = '" & VBatch & "'")
Forms!ChangeOrders.ChangeOrderSubform.Form.Availability.Value = VAvail
That's all that is needed.

Access 2010 set variable to single field of a table

I feel like this should be easy, but I haven't been able to come up with a clear answer for this after searching off and on all day.
I have a users table that has email addresses in it.
I have a combo box that references this table.
All I want to do, is set the email address field of the selected user to a string, so I can then do things with that.
just trying to get a string back from a sql query like :
"SELECT emailAddress FROM tblUsers WHERE id = " & Me.cmbUser.Value & ""
Can someone point me in the right direction here?
You can use Combo Box to return email address after user select user from list.
Assume your user tblUsershas User and Email fields
Set your combo box property:
1.Row Source = SELECT User, Email FROM tblusers
2.Column Count = 2
3.Bound Column = 0 (0 is the first column and 1 is the second column which is email)
4.Column width = x";0" (x is your combox box width)
You can get email address from me.combobox.column(1). Both me.combobox.value and me.comboxbox.column(0) is selected User
If you actually want to execute the query, you have multiple options:
You can use DLookup:
TL;DR:
DLookup("Column", "Table", "Col=Value") will execute SELECT Column FROM Table WHERE Col=Value and return the first row.
For the query from your question, you need to use DLookup like this:
Dim mail As String
mail = Nz(DLookup("emailAddress", "tblUsers", "id = " & Me.cmbUser.Value))
You can load your SQL query with a Recordset.
This makes more sense than DLookup if you need more user data from the table than just the email adress.
Dim mail As String
Dim phone As String
Dim RS As DAO.Recordset
Set RS = CurrentDb.OpenRecordset("SELECT emailAddress, phoneNumber FROM tblUsers WHERE id = " & Me.cmbUser.Value)
If Not RS.EOF Then
mail = Nz(RS("emailAddress"))
phone = Nz(RS("phoneNumber"))
End If
RS.Close
Set RS = Nothing
(in order for this to work, your Access database needs a reference to any version of the Microsoft DAO Object Library...this should already be the case in most newer Access versions)
Note the usage of Nz in both examples - this is necessary if the mail adress can be NULL. Without Nz, the code would crash because of setting a string variable to NULL.

How do take the value from a combobox and use it to run an SQL query

I am trying to take the value from a combo box (in this case 'cboFullName' located on form 'frmMasterNotebook') and cross reference it to table 'tblSearchEngine01' so that an update gets made to column 'query05contactselect' for all records where in column 'contact' the value matches to that selected by the combobox ('cboFullName'). Below is my code but I am getting a syntax error message.
Private Sub cboFullName_AfterUpdate()
st_sql = "UPDATE tblSearchEngine01, SET tblSearchEngine01.Query05ContactSelect = '1' WHERE (((tblSearchEngine01.[contact])=([forms]![frmmasternotebook]![cbofullname]))))"
Application.DoCmd.RunSQL (st_sql)
Your code builds an UPDATE statement which includes a comma after the table name ...
UPDATE tblSearchEngine01, SET
^
Remove that comma and see whether Access complains about anything else.
However I suggest you start by creating and testing a new query in Access' query designer. Paste this statement into SQL View of your new query ...
UPDATE tblSearchEngine01
SET Query05ContactSelect = '1'
WHERE [contact] = [forms]![frmmasternotebook]![cbofullname];
After you revise and test the statement so that Access executes it without complaint, then you can revise your VBA code to produce the exact same statement text which works in the query designer.
Using DAO this is another way to resolve my issue:
Private Sub cboFullName_AfterUpdate()
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tblSearchEngine06", dbOpenTable)
rst.AddNew
rst!Contact = Me.cboFullName.Text
rst!ContactID = Me.cboFullName
rst.Update
rst.Close
Set rst = Nothing

Date Subtraction within Select Statement

I am currently working on an MS Access database, and am having problem with date subtraction.
Essentially I am trying to create a target date for example:
Target Date = Deadline - Lead Time
i.e. the lead time could be 30 days, therefore the target date should be 30 days prior to the deadline.
The code I am trying to use is this:
strSQL = "INSERT INTO dbo_DEALER_TASK ( Dlr_Number, Action_Id, Task_Id, Area_Id,
Task_Deadline_Date, Responsible_Person_Id, Alternate_Person_Id, Priority, Comment,
Suppress_Email, Dealer_Type ) "
strSQL = strSQL & "SELECT dbo_DEALER_ACTION.Dlr_Number, dbo_DEALER_ACTION.Action_Id,
qryAllTasksToAdd.Task_Id, qryAllTasksToAdd.Area_Id, Deadline_Date - Deadline_adjustment
AS 'Task_Deadline_Date', qryAllTasksToAdd.Person_Responsible_Id,
qryAllTasksToAdd.Alternate_Responsible_Id, qryAllTasksToAdd.Priority,
qryAllTasksToAdd.Comment, qryAllTasksToAdd.Suppress_Email,
qryAllTasksToAdd.Applies_To_Dealer_Type "
strSQL = strSQL & "FROM dbo_DEALER_ACTION LEFT JOIN qryAllTasksToAdd ON
(dbo_DEALER_ACTION.Dealer_Type = qryAllTasksToAdd.Applies_To_Dealer_Type) AND
(dbo_DEALER_ACTION.Action_Id = qryAllTasksToAdd.Action_Id) "
strSQL = strSQL & WHERE (((qryAllTasksToAdd.Task_Id)=" & Me.Task_Id & ") AND
((dbo_DEALER_ACTION.Date_Completed) Is Null));"
DoCmd.RunSQL strSQL
When the VBA code executes the statement, everything is updated correctly, except for the Task_Deadline_Date field, which is being left blank.
What is really confusing me though is if I run this SQL statement standalone it is working as expected. After trying a number of different ideas I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
Does anybody have any ideas what is going wrong?
Thanks,
Chris
You have quoted the alias, you should not do that:
Deadline_Date - Deadline_adjustment AS Task_Deadline_Date
Not
Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'
When you add the quotes, the name of the field is 'Task_Deadline_Date'
Depending on the data type of your date field and whether or not you are using SQL Server, you may need to use DateAdd, for example:
DateAdd("d",-[Deadline_adjustment],[Deadline_Date])
In Access' query designer, start with the version of your query which works and convert it to a parameter query.
WHERE
qryAllTasksToAdd.Task_Id=[which_id]
AND dbo_DEALER_ACTION.Date_Completed Is Null;
You can also add a PARAMETERS statement at the start of the query to inform the db engine about the data type of your parameter. Examples ...
PARAMETERS which_id Text ( 255 );
PARAMETERS which_id Long;
Once you get that query working, save it and give it a name. Then your VBA procedure can use that saved query, feed it the parameter value, and execute it.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("YourQuery")
qdf.Parameters("which_id").value = Me.Task_Id
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
This should be much easier than trying to recreate that SQL statement in VBA code each time you need to execute it.
It sounds like the data type of the column you are inserting in dbo_DEALER_TASK is not actually a datetime field.
I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
If you mean '02/20/2012' (as you would correctly use on SQL Server, for example) then this shouldn't work in Access and only will if your output column is a text (= varchar/char)) data type. Date constants in Access are specified like #02/20/2012#
Please confirm the data type of Task_Deadline_Date in your output table.

Categories