Date / Timestamp to record when a record was added to the table? [duplicate] - sql

This question already has answers here:
How do I add a "last updated" column in a SQL Server 2008 R2 table?
(2 answers)
Closed 8 years ago.
Does anyone know of a function as such that I can use to add an automatic date and timestamp in a column for when a user adds a record to the database table?

You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.
e.g.
CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)

You can make a default constraint on this column that will put a default getdate() as a value.
Example:
alter table dbo.TABLE
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN

You can use a datetime field and set it's default value to GetDate().
CREATE TABLE [dbo].[Test](
[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
[Foo] [varchar](50) NOT NULL
) ON [PRIMARY]

You can pass GetDate() function as an parameter to your insert query
e.g
Insert into table (col1,CreatedOn) values (value1,Getdate())

you can use DateAdd on a trigger or a computed column if the timestamp you are adding is fixed or dependent of another column

Related

Adding a computed column in Postgres SQL based on a date

Here my table.
CREATE TABLE annual_goals (
id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
content TEXT NOT NULL,
complete BOOLEAN DEFAULT false,
date_created TIMESTAMP DEFAULT now() NOT null,
date_modified TIMESTAMP DEFAULT now() NOT null
);
I want to alter it such that I can add a new column called month_num that returns the number of the month given date_created (i.e. if the date_created of an entry is 5/31/2019, I want the month_num to automatically populate 5).
I tried the following but I'm getting an error that states "ERROR: syntax error at or near "A
S"
ALTER TABLE annual_goals
ADD year_num
AS year(date_created);
Any help is greatly appreciated. Thanks
You have two errors in the code. One is that MySQL requires the type. The second is that the expression needs to be surrounded by parentheses:
ALTER TABLE annual_goals ADD year_num int AS ( year(date_created) );
EDIT:
In Postgres, you can use the syntax:
alter table annual_goals
add year_num int generated always as (extract(year from date_created)) stored;
Here is a db<>fiddle.
You could try this:
ALTER TABLE annual_goals
ADD year_num int;
UPDATE annual_goals
SET year_num=year(date_created);

Garbage value appear in a column instead of default value

I have a columns called From_date and to_date. The columns have default constraint as getdate() and 9999-12-31 respectively.
But I got something strange after loading data to table.
Instead of default value I am getting value in both the column as 1753-01-01 00:00:00.0000000
Has anyone came across this situation? How to solve this issue?
Here is some of the table DDL
ALTER TABLE [dbo].[mytable]
ADD CONSTRAINT [df_FMDT_IX]
DEFAULT (getdate()) FOR [from_date]
GO
ALTER TABLE [dbo].[mytable]
ADD CONSTRAINT [df_TODT_IX]
DEFAULT ('9999-12-31') FOR [to_date]
GO
DATATYPE FOR THE COLUMN IS DATETIME2
That date you're seeing is the minimum date value in SQL.
What is the significance of 1/1/1753 in SQL Server?
I'm assuming someone's entered a zero in that column which will display as the min possible value.

Invalid Datatype trying to alter table [duplicate]

This question already has answers here:
Set ORACLE table fields default value to a formular
(2 answers)
Closed 8 years ago.
I got a table which I used the below code to create.
create table Meter (MeterID CHAR(8) CONSTRAINT MeterPK PRIMARY KEY,
Value CHAR(8) CONSTRAINT ValueNN NOT NULL,
InstalledDate Date CONSTRAINT InDateNN NOT NULL);
Then I tried adding a derived column that adds 6 months to the installeddate.
alter table meter add ExpiryDate as (add_months(installedDate,6)) not null;
This returns an error of invalid datatype.
I read somewhere that I do not have to specify the datatype of ExpiryDate as it can be derived from the function. So where did I go wrong?
EDIT: Turns out Mike was right. I used the trigger method to get things going, but I was confused whether I'm using mysql or oracle. Think in the end I'm using oracle actually. Have problems with the trigger but turns out I do not need to have the command "set" in the trigger. Below is the code that works.
CREATE OR REPLACE
TRIGGER trigexpdate1
BEFORE INSERT ON Meter
FOR EACH ROW
BEGIN
:NEW.ExpiryDate := ADD_MONTHS(:NEW.InstalledDate, 6);
END;
If I don't have the begin and end in the statement, it will throw an error saying illegal trigger specification.
MySQL doesn't support
derived columns in table definitions,
a function named add_months(), or
inline constraints.
This is a more or less standard way to write that statement in MySQL.
create table `Meter` (
`MeterID` CHAR(8) NOT NULL,
`Value` CHAR(8) NOT NULL,
`InstalledDate` Date NOT NULL,
primary key (`MeterID`)
);
You have two options for a derived column like "ExpiryDate".
Create a view, and do the date arithmetic in the view. Use date_add().
Add the column "ExpiryDate" to the table, and keep it up-to-date with a trigger.
BEFORE INSERT trigger example
create table `Meter` (
`MeterID` CHAR(8) NOT NULL,
`Value` CHAR(8) NOT NULL,
`InstalledDate` Date NOT NULL,
`ExpiryDate` Date not null,
primary key (`MeterID`)
);
create trigger trigexpdate1
before insert on `Meter`
FOR EACH ROW
SET NEW.`ExpiryDate` = date_add(NEW.`InstalledDate`, interval 6 month);
Note how ExpiryDate changes from the insert statement to the select statement below.
insert into Meter
values ('1', '1', '2014-07-01', '2014-07-01');
select * from Meter;
MeterID Value InstalledDate ExpiryDate
--
1 1 2014-07-01 2015-01-01

how to add today date as default value in sql server

in sql server. my database name RequestInfo, I have a table name RequestedDate, which have data type is datetime. now i want when ever the value of other columns of table is inserted, then automatically in the RequestedDate column, today date should inserted.
i am using this query but it shows no today in built function.
alter table RequestInfo add default Today() for RequestedDate
Define Default Value When Creating Table
CREATE TABLE TestTable
(
ID INT PRIMARY KEY NOT NULL,
DATECOLUMN DATETIME DEFAULT GETDATE() --<-- Default Value
)
Already Existing Table on already Existing Column
ALTER TABLE TestTable
ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR DATECOLUMN
Add a new Column to an Existing Table With Default Value
ALTER TABLE TestTable
ADD New_DATE_COLUMN DATETIME DEFAULT GETDATE()
This worked for me:
ALTER TABLE YOUR_TABLE ADD Date_Created TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

Default getdate for Insert date

I have a table called sample and it has a column called [__INSERT_DATE] which is null. Now I want to alter the column with default as getdate(). When I tried the following it gave me an error.
ALTER TABLE sample
ALTER COLUMN [__INSERT_DATE] [datetime] DEFAULT (getdate()) NULL)
Can anyone tell me what the problem is?
Try this:
ALTER TABLE MyTable ADD CONSTRAINT
DF_MyTable_Inserted DEFAULT GETDATE() FOR INSERT_DATE
GO
This assumes your table is named MyTable, the column is INSERT_DATE, and the name of the contstraint is to be DF_MyTable_Inserted
Try this:
ALTER TABLE sample ADD CONSTRAINT DF_sample___INSERT_DATE DEFAULT(GETDATE()) FOR __INSERT_DATE
ALTER TABLE sample ADD INSERT_DATE [datetime] NOT NULL DEFAULT GetDate()
This will works in Microsoft SQL Server
MSDN gives this example:
ALTER TABLE MyCustomers ALTER COLUMN CompanyName SET DEFAULT 'A. Datum Corporation'
That would give you
ALTER TABLE sample ALTER COLUMN __INSERT_DATE SET DEFAULT GETDATE()
I was able to do it using SSManagement Studio
make the date field not nullable, then from properties
set Defalut Value or Binding to getdate()
ALTER TABLE sample
ALTER COLUMN [__INSERT_DATE] [datetime] DEFAULT (getdate()) NULL)
You have one too many closing brackets in the above statement. There are 2 of these -> ( but 3 of these -> )
(Your_Date_Column) Make it Null / Not Null and give default value GetDate() but still it will not work.
You have to create a trigger like this,
CREATE TRIGGER [dbo].[Trigger_Date]
ON [dbo].[TableName]
FOR INSERT
AS
BEGIN
Declare #Id int
set #Id = (select Id from inserted)
Update [dbo].[TableName]
Set Your_Date_Column = GetDate()
Where Id = #Id
END
This way worked for me:
ALTER TABLE sample ALTER COLUMN INSERT_DATE [datetime] NULL DEFAULT GetDate()
If you already have values in the column, you can do something like this:
Alter Table sample add INSERT_DATE_TEMP [datetime] NOT NULL DEFAULT GetDate()
Update sample
SET INSERT_DATE_TEMP = INSERT_DATE
Alter Table sample Drop Column INSERT_DATE
exec sp_rename 'sample.INSERT_DATE_TEMP','INSERT_DATE','COLUMN'
Does getdate() return the correct date and time datatype for your declared column? There are some new date and time datatypes in SQL Server 2008.
Here's an article that explains some of the differences.
http://www.sql-server-performance.com/articles/dev/datetime_2008_p1.aspx