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 ...
Related
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.
Code below, but the date in the table is not showing correctly, my computer system date is set to yyyy,mm,dd and the Access table field is selected to short date. As seen in code below the date is showing fine when debugging and stepping through the program but at the end the date in the table is shown as 1905-12-30 (Which should be 2013-12-30) any suggestions please?
InsDate = Date
**InsDate** = Format(InsDate, "yyyy,mm,dd")
AppeQry = "INSERT INTO TStockMaster ( SupplierID, PartID, UnitsID, ConditionID, " & _
"QTY, WarehouseID, BinID, RowID, ColumnID, InsDate ) VALUES ( " & SupID & "," & PrtID & "," & UntID & "," & _
CondID & "," & Qt & "," & WarehID & "," & BnID & "," & RwID & "," & ColID & "," & **InsDate** & ");"
Use a parameter query instead of concatenating values as text into an INSERT statement.
Then, when you execute the statement, and supply the parameter value, you can give it the actual Date/Time value and not be bothered with text format and date type delimiters.
Here is a simplified example. Save this query as qryTStockMasterAppend.
INSERT INTO TStockMaster (InsDate) VALUES (pInsDate);
Then your VBA code can use that saved query, supply the parameter value and execute it.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("qryTStockMasterAppend")
qdf.Parameters("pInsDate") = Date()
qdf.Execute dbFailOnError
Thank you beforehand for your assistance. I know enough about Access, SQL, and VBA to get myself into trouble. Here is what I want to do.
I want to create a query that starts with a certain year and then lists each year up until the current year. The problem is that I want the query to automatically update as time progresses. In other words, say the start year is 2009, I want my query to list 2009, 2010, 2011, 2012, and 2013 since we are currently in the year 2013. Next year, the list will expand to include 2014. I suspect this is possible using a query in SQL but not sure how to go about coding it properly.
I bet that there is no simple solution for this simple process. We must use VBA to perform following steps:
Create a temporary table:
CREATE Table tblTmpYears (
ID COUNTER CONSTRAINT PrimaryKey PRIMARY KEY,
Year Long
);
In VBA:
Dim strSQL
strSQL = "CREATE Table tblTmpYears (" _
& " ID COUNTER CONSTRAINT PrimaryKey PRIMARY KEY," _
& " Year Long" _
& ");"
CurrentDb.Execute strSQL, dbFailOnError
Fill the temporary table:
INSERT INTO tblTmpYears (year) VALUES (2009);
INSERT INTO tblTmpYears (year) VALUES (2010);
INSERT INTO tblTmpYears (year) VALUES (2011);
INSERT INTO tblTmpYears (year) VALUES (2012);
INSERT INTO tblTmpYears (year) VALUES (2013);
In VBA, for 5 years, valid even after 100 years after our life existence:
Dim y as long, ymin, ymax, strSQL
ymax = Year(Date)
ymin = ymax - 4
For y = ymin to ymax
strSQL = "INSERT INTO tblTmpYears (Year) VALUES (" & y & ");"
CurrentDb.Execute strSQL, dbFailOnError
Next
Create a query for listing with the temporary table:
SELECT * FROM tblStudents INNER JOIN tblTmpYears
ON tblStudents.Year=tblTmpYears.Year
ORDER BY Year;
In VBA like this:
Dim qdf, strSQL
strSQL = "SELECT * FROM tblStudents INNER JOIN tblTmpYears" _
& " ON tblStudents.Year=tblTmpYears.Year" _
& " ORDER BY Year;"
Set qdf = CurrentDB.CreateQueryDef("qrySelTemporary", strSQL)
DoCmd.OpenQuery qdf.Name
Here you will have the Query Datasheet Windows with your students's list, it's printable. Even better, you can use it as
MyReport.RecordSource = "qrySelTemporary"
in an Access Report with a beautiful presentation.
Delete the temporary table after printing, for example:
DROP TABLE tblTmpYears;
In VBA:
Dim strSQL
strSQL = "DROP TABLE tblTmpYears;"
CurrentDb.Execute strSQL, dbFailOnError
Only VBA can accomplish this... rather than a single SQL query.
How about this - a small VBA function that outputs the SQL for an appropriate UNION query, which you can then assign as the RowSource for a combo box, use as a sub-query inside another dynamically generated query, or whatever:
Function CreateYearsToCurrentSQL(From As Integer) As String
Dim I As Integer, S As String
For I = From To Year(Date)
If I <> From Then S = S + "UNION "
S = S + "SELECT " & I & " AS Year FROM MSysObjects" + vbNewLine
Next I
CreateYearsToCurrentSQL = S
End Function
The FROM MSysObjects is because Access will whinge about no FROM clause if one isn't there, and MSysObjects is bound to be an existing table in an Access context (if you prefer though, replace it with the name of any other table).
So I managed to create a Query Criteria that does what I need.
Like (Right(Year(Now()),2)-3) & "-" Or Like (Right(Year(Now()),2)-2) & "-" Or Like (Right(Year(Now()),2)-1) & "-" Or Like Right(Year(Now()),2) & "-"
Thank you everyone for your efforts.
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 & "')"