I am writing a number of scripts to update numerous Access tables. I would like to add a column to each that has a field called "date_created" that is a timestamp of when the record is created. Doing this through the table view is simple, simply set the DefaultValue = now(). However, how would I accomplish this in sql?
This is my current attempt for tables that already have the column. This example uses "tblLogs".
ALTER TABLE tblLogs ALTER COLUMN date_created DEFAULT now()
Thanks for your help!
Update - Would there be a way to do this in VBA?
Update 2 - Tested all of the answers and the following by onedaywhen is the shortest and most accurate
CurrentProject.Connection.Execute _
"ALTER TABLE tblLogs ALTER date_created DATETIME DEFAULT NOW() NOT NULL;"
In SQL Server it's getdate().
SQL Server GETDATE() Function The GETDATE() function returns the current database system date and time, in a 'YYYY-MM-DD hh:mm:ss.
I'm assuming:
CURRENT_TIMESTAMP
in Standard SQL (not directly supported by ACE/Jet, though) and not to be confused with SQL Server's TIMESTAMP
data type;If you created your table using this SQL DDL:
CREATE TABLE tblLogs
(
date_created DATETIME NOT NULL
);
then the following SQL DDL would add the DEFAULT
your require:
ALTER TABLE tblLogs ALTER
date_created DATETIME DEFAULT NOW() NOT NULL;
The above ACE/Jet SQL syntax is ANSI-92 Query Mode flavour. To use this via the MS Access interface (e.g. a Query object's SQL view) see Microsoft Office Access: About ANSI SQL query mode (MDB). To do this programmatically using SQL DDL requires (AFAIK) the use of OLE DB, which in VBA requires (AFAIK) the use of ADO. DAO always uses ANSI-89 Query Mode syntax, whose SQL DDL syntax lacks support for DEFAULT
.
If you are using Access (rather than ACE/Jet standalone), you can use a single line of VBA (ADO) code:
CurrentProject.Connection.Execute "ALTER TABLE tblLogs ALTER date_created DATETIME DEFAULT NOW() NOT NULL;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With