I am inserting data from table tbl_login to table LoginHistory with date stamp. But I am confused to add Date Stamp with query string.
My Code is:
strSQL2 = "SELECT UserID, FirstName, LastName, UserName FROM tbl_login WHERE Username = """ & Me.txt_username.Value & """ AND Password = """ & Me.txt_password.Value & """"
strSQL3 = "INSERT INTO LoginHistory (UserID, FirstName, LastName, UserName, LoginDate)" & strSQL2 & Now()
CurrentDb.Execute strSQL3
Can't tack on Now() after strSQL2 because that puts it after the FROM and WHERE clauses. Put it into strSQL2 statement. The SQL engine can evaluate Now() function. Can use a single apostrophe in place of double quotes as delimiter character.
strSQL2 = "SELECT UserID, FirstName, LastName, UserName, Now() AS CD FROM tbl_login WHERE Username = '" & Me.txt_username & "' AND Password = '" & Me.txt_password & "'"
strSQL3 = "INSERT INTO LoginHistory (UserID, FirstName, LastName, UserName, LoginDate)" & strSQL2
CurrentDb.Execute strSQL3
Why even duplicate UserName, FirstName, LastName into LoginHistory? Just save UserID and Now().
I would rather add Now() as a default value for your LoginDate field. This way you won't have to take care about that in any query.
I think it's always better to implement such thinks at the lowest level: the table definition, in this case.
Related
Have been trying to insert a Street, Suburb and a postcode into a table but keep getting
Run-time error '13'
Type mismatch
Here is the code:
Sub arrayData()
Dim CustomerNames() As Variant
Dim num As Long, dbs As Database, InsertReocrd As String
Dim CustomerID As Long, num1 As Long
Dim CustomerName As String
Dim Street As String, Suburb As String, Postcode As Integer
Set dbs = CurrentDb()
CustomerID = 0
For num1 = 0 To 50000
CustomerID = CustomerID + 1
CustomerNames = Array(...)
Street = Array("Short", "Lygon", "Flinders", "Elizabeth", "King") //ERROR OCURRS HERE
Suburb = Array("Sandringham", "Brighton", "St Kilda", "Melbourne", "Carlton") //ERROR OCURRS HERE
Postcode = Array("3165", "3298", "3145", "3144", "3000") //ERROR OCURRS HERE
num = Int((250 - 0 + 1) * Rnd + 0)
CustomerName = CustomerNames(num)
InsertRecord = "INSERT INTO CUSTOMER (CustomerID , CustomerName, StreetName, Suburb) VALUES (" & "'" & CustomerID & "'" & "," _
& "'" & CustomerName & "'" & "'" & StreetName & "'" & ")"
dbs.Execute InsertRecord
Debug.Print CustomerID, CustomerName, Street, Suburb
Next
End Sub
Variables that should hold arrays need to be declared as Variant, not as String.
So:
Dim Street As Variant, Suburb As Variant, Postcode As Variant
Note that your INSERT statement is missing the value for Suburb.
Using DAO.Recordset.AddNew etc. would probably be faster and better readable.
As shown yesterday, simplify your concatenation, and you also need and array for the CustomerID and a loop as well:
For n = 1 To 5
InsertRecord = "INSERT INTO CUSTOMER (CustomerID , CustomerName, StreetName, Suburb) VALUES (" & CustomerID(n) & ",'" & CustomerName(n) & "','" & StreetName(n) & "','" & Suburb(n) & "')"
If you really wish to insert 50000 customers this way(?) (you wouldn't), follow the advice from André and use DAO.
Sorry if this doesn't exactly fit the topic. Just in case any other poor fool spends hours trying to figure out why they're getting a 'Type Mismatch' on a VBA recordset.addnew, check the [Default Values] of the fields/columns in the table. I changed a TEXT field to a DATE field, but neglected to remove the "" in [Default Value]. (trying to set any text value to a date field is a no-no).
I would like to know what I should do to insert some dates into a table. My table has 4 columns:
ID (AutoNumber)
First_Name
Last_Name
Date
I would like to insert some data with VBScript. Here is what I have so far:
sub DBinsert(fname, lname)
Set objCon= CreateObject("ADODB.Connection")
Set RS1 = CreateObject("ADODB.Recordset")
WScript.echo "DBInsert"
objCon.Open "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\bonhkarl01\Desktop\Blank database.mdb"
objCon.execute(" Insert into table3(First_Name, Last_Name, Date) Values ('" & fname & "','" & lname & "','" & Date() & "') ")
End sub
It worked so far when I tried without the "Date" in another table... Is there anything wrong with the objCon.execute command?
The error I am getting is
Syntax error in INSERT INTO statement.
Date is a reserved word in Access SQL. If you need to refer to a column named Date then you must enclose it in square brackets.
objCon.execute(" Insert into table3 (First_Name, Last_Name, [Date]) Values ...
I have created a VBA function that selects some data from an Access table and puts that data into a temp table. I want to change the format of a date column using the following code so that the date has the leading '0'.
Dim lValue As String
lValue = Format(Transaction_Date, "mm/dd/yyyy")
Dim i As Integer
SQL = "SELECT ID, PO_Number, Vendor_Company, Incurred_By, Transaction_Type, lValue as Transaction_Date, Investment_ID, " & _
"Notes, Quantity INTO tmp_Tran_Actual FROM Transaction_Data"
DoCmd.RunSQL SQL
When the code runs, I am prompted to enter the value, in this case the date, for 'lValue'.
I tried adding the Format(Transaction_Date, "mm/dd/yyyy") into the select query, but the quotes in the format function would make the whole row seem like it was all text.
The db engine is unaware of the VBA variable, so assumes it must be a parameter when it sees the variable name.
Build the variable's value into the SQL string and surround it with the # delimiter to indicate it's a Date/Time value.
SQL = "SELECT ID, PO_Number, Vendor_Company, Incurred_By, " & _
"Transaction_Type, #" & lValue & "# as Transaction_Date, " & _
"Investment_ID, Notes, Quantity INTO tmp_Tran_Actual FROM Transaction_Data"
If you actually wanted Transaction_Date as a formatted string, surround the value with single quotes instead of #.
SQL = "SELECT ID, PO_Number, Vendor_Company, Incurred_By, " & _
"Transaction_Type, '" & lValue & "' as Transaction_Date, " & _
"Investment_ID, Notes, Quantity INTO tmp_Tran_Actual FROM Transaction_Data"
Or maybe this is what you had in mind all along ...
SQL = "SELECT ID, PO_Number, Vendor_Company, Incurred_By, " & _
"Transaction_Type, Format(Transaction_Date, 'mm/dd/yyyy') as Transaction_Date, " & _
"Investment_ID, Notes, Quantity INTO tmp_Tran_Actual FROM Transaction_Data"
I have a button which uses two separate queries that pull data from two tables and insert into another table:
Dim lngID As Long
Dim lngIDCallout As Long
Dim strSQL1 As String
lngID = CalloutAttendance_MultiSelect.Value
lngIDCallout = Forms![Callouts].[CalloutID].Value
strSQL1 = "INSERT INTO Members_Callouts(MemberID) SELECT MemberID FROM Members WHERE MemberID=" & lngID
strSQL2 = "INSERT INTO Members_Callouts(CalloutID) SELECT CalloutID FROM Callouts WHERE CalloutID=" & lngIDCallout
CurrentDb.Execute strSQL1
CurrentDb.Execute strSQL2
CalloutAttendance_MultiSelect.Requery
And whilst it almost does what I want it to do, it inserts the the two values as two separate new records, whereas I'd like it to insert it into ONE new record. I've had a go, but I either get syntax errors, or in the case below, I got a 3067 runtime error "Query input must contain at least one table or query"
strSQL1 = "INSERT INTO Members_Callouts(MemberID, CalloutID) SELECT
(SELECT MemberID FROM Members WHERE MemberID=" & lngID & "),
(SELECT CalloutID FROM Callouts WHERE CalloutID=" & lngIDCallout & ")"
Anyone know where I might be going wrong?
Thanks :-)
In this case you're just inserting the key values so all you need to do is
strSQL1 = _
"INSERT INTO Members_Callouts (MemberID, CalloutID) " & _
"VALUES (" & lngID & ", " & lngIDCallout & ")"
In other words, you don't need to bother with something like...
"(SELECT MemberID FROM Members WHERE MemberID=" & lngID & ")"
...since the value it returns is just lngId (assuming that the value exists in the [Members] table).
INSERT INTO
MyTable (Col1,Col2,Col3,Col4,Col5,Col6,Col7)
SELECT
f1.col1, f2.col2, f3.col3, f3.col4, f3.col5, f4.col6, f5.col7
FROM
(SELECT Col1 FROM Func1()) AS f1
CROSS JOIN
(SELECT Col2 FROM Func2()) AS f2
CROSS JOIN
(SELECT Col3,Col4,Col5 FROM Func3()) AS f3
CROSS JOIN
(SELECT Col6 FROM Func4()) AS f4
CROSS JOIN
(SELECT Col7 FROM Func5()) AS f5
I have to make an audit trail that can keep track of the fields after INSERT INTO, however, I can't get any of the variables the expressions in "values" represents to go into the fields, only the expressions in VALUES. For instance, the two entries with numeric values give me numeric values, the others give me a string that is for instance Form.RecordSource = clientName
db.Execute "INSERT INTO tblAudit ([RecordID], [AuditWho], [AuditWhen], [AuditWhat], [AuditFrom], [AuditTo]) VALUES ('1', '2', 'Now()', 'Form.RecordSource = clientName' , ' Me.ClientName.Value ', ' Me.clientNameTextBox.Value ')"
At a minimum you need to do something like this:
Dim SQL as string
SQL = "INSERT INTO tblAudit ([RecordID], [AuditWho], [AuditWhen], [AuditWhat], [AuditFrom], [AuditTo]) VALUES ('1', '2','" & Now() & "', 'ClientName' , '" & Me.ClientName.Value & "', '" & Me.clientNameTextBox.Value & "')"
db.Execute SQL
To be more "robust" you should declare variables for AuditFrom and AuditTo values and validate that the data entered is "ok" before trying to perform the insert:
Dim SQL as string
dim strAuditFrom as string
Dim strAuditTo As String
strAuditFrom = Me.ClientName.Value & ""
strAuditTo = Me.ClientNameTextBox.Value & ""
if strAuditTo = vbNullString then
'Alert the user or throw an error perhaps?
end if
sql = "INSERT INTO tblAudit ([RecordID], [AuditWho], [AuditWhen], [AuditWhat], [AuditFrom], [AuditTo]) VALUES ('1', '2','" & Now() & "', 'ClientName' , '" &strAuditFrom & "', '" & strAuditTo & "')"
db.Execute sql
You're defining the text to insert by using the single qoutes. To get a value from a control and have it included in your query you need to escape the string using a double qoute, concatacate the string with the ampersand, find the value of the control, and continue the string with the ampsand and double qoute. For example:
db.Execute "INSERT INTO tblOne (Field1, Field2) VALUES ('literal text','" & ctlSomething & "')"