How to make created_at and updated_at fields in MsSQL? [duplicate] - sql-server

This question already has answers here:
Need a datetime column in SQL Server that automatically updates when the record is modified
(5 answers)
Closed last month.
I want to make created_at and updated_at in MsSQL.
Here is query:
CREATE TABLE current_timestamp_demos
(
id INT PRIMARY KEY IDENTITY (1, 1),
msg VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
);
With created_at everything is fine, but on filed updated_at - here, ON UPDATE CURRENT_TIMESTAMP I get an error. DataGrip say something about dialect, and this is MySQL dialect, I guess.
So, how can I create those created_at and updated_at fields? I've created created_at, but with updated_at I have some problems.

The complete code :
CREATE TABLE current_timestamp_demos
(
id INT PRIMARY KEY IDENTITY (1, 1),
msg VARCHAR(255) NOT NULL,
created_at DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
updated_at DATETIME2
);
GO
CREATE TRIGGER E_U_CTD
ON current_timestamp_demos
FOR UPDATE
AS
UPDATE T
SET updated_at = SYSDATETIME()
FROM current_timestamp_demos AS T
JOIN inserted AS i
ON T.id = i.id;
GO
Also use SYSDATETIME() instaed of CURRENT_TIMESTAMP.

Related

How to manage an ImportHistory in a Database?

I have a table ImportHistory in which I store history of importation. (Each time the user upload a file I store a row).
CREATE TABLE [dbo].[ImportHistory]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Date] TIMESTAMP NOT NULL,
CONSTRAINT [PK_ImportHistory] PRIMARY KEY ([Id])
)
And I have also
CREATE TABLE [dbo].[Sales] (
[Id] VARCHAR (150) NOT NULL,
...
[ImportHistoryId] INT NOT NULL,
...
CONSTRAINT [FK_Sales_ImportHistory] FOREIGN KEY ([ImportHistoryId]) REFERENCES [dbo].[ImportHistory] ([Id])
);
The question is how to properly take the ID of ImportHistory and store it each time I insert a line in SALES for this import session ?
You insert a row in ImportHistory.
You SELECT SCOPE_IDENTITY() to get the ID of the newly created record.
You insert your Sales records, using the value acquired in Step 2 as the ImportHistoryID.
PS: The timestamp data type is not what you think it is. You probably want to use date or datetime2 instead.

add a constraint on a datetime column

i want to to add a constraint onto a ID column and a date time column, so that an id can only be entered once in a day
alter table Table1
...
add constraint pk_id Primary Key (datetime,ID)
If an id has been inserted for the following datetime 2015-03-17 12:48:00, it would not get inserted again on the same datetime, but if the time changes to 2015-03-17 12:45:00 the id gets entered again.
Is there a way to add the constraint to just the date part of the datetime column?
I don't think you can but you have different alternatives:
Change your column to just have the date part populated
Create a computed column where you remove the time part and create the unique index used this column instead.
EDIT: as per #a-ツ comment there are other options:
Split the column in two, one to store the date and other to store the time part, so you can create de index over the date one
You have to give composite primary key or check constraint..
Check this example. For composite key, on design mode, just select both column and right click and select "primary-key".
CREATE TABLE [dbo].[Table_1](
[id] [int] NOT NULL,
[datecolumn] [datetime] NOT NULL,
[name] [varchar](50) NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[id] ASC,
[datecolumn] ASC
)
) ON [PRIMARY]
GO
insert into Table_1 values (1, '2014-03-17 00:00:00.000', 'othercolumnvalue')
insert into Table_1 values (1, '2014-03-17 12:00:00.000', 'othercolumnvalue')
insert into Table_1 values (1, '2014-03-17 02:10:59.000', 'othercolumnvalue')
--this will give error as you already entered the same value.
insert into Table_1 values (1, '2014-03-17 00:00:00.000', 'othercolumnvalue')
how do I make a composite key with SQL Server Management Studio?

How can I add a timestamp column to my SQL Server table when I create it?

I am trying to use the following:
CREATE TABLE [dbo].[Application] (
[ApplicationId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
timestamp
CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
);
Can someone confirm if this is the correct way. Also can or should I give that column a name of its own?
* Note that I am using Entity Framework. So is it okay to add a column like this but to not add it to the Application object?
I think that timestamp is a poor name for that datatype (it does not store time) and somewhere along the way Microsoft did too and has deprecated the use of timestamp since SQL Server 2008 in favor of rowversion introduced in SQL Server 2000.
Your code uses a behavior of timestamp that it gives the column a default name, rowversion does not do that so you have to give the column a name.
CREATE TABLE [dbo].[Application] (
[ApplicationId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
VerCol rowversion
CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
);
Ref:
rowversion (Transact-SQL)
timestamp SQL Server 2000
* Note that I know nothing about using Entity Framework.
CREATE TABLE [dbo].[Application] (
[ApplicationId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
timestamp DATETIME NULL DEFAULT GETDATE()
CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
);
To add the timestamp / rowversion to an existing table you can do this.
ALTER Table OrderAction ADD [RowVersion] rowversion not null
It will automatically assign timestamps, you don't need to anything like UPDATE rowversion = getdate()
Please note that if your table is large it can take a while since it needs to add a timestamp for every row. If you have a huge table and you're using a scalable database like Azure SQL you might want to increase capacity first and/or do it during off hours.
timestamp data type is identical to rowversion datatype - it's just up to you what you call the column.
It also doesn't need to be in your data model to be updated by an UPDATE or INSERT. However if it isn't in your data model then you won't actually benefit from the whole point of it which is to get a simplified UPDATE like this:
WHERE ([OrderId] = #p0) AND ([RowVersion] = #p1)

What to use in DB2 for CURRENT_TIMESTAMP?

I am converting some of my MySQL statements to DB2 database, but I faced a problem on the following query
CREATE TABLE RFX_EVENT_MAPPING (
EVENT_TYPE varchar(4) NOT NULL,
EVENT_DESC varchar(50) NOT NULL,
EVENT_CLASS varchar(50) default NULL,
OWNER varchar(6) default NULL,
LAST_UPDATE_TIME timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
LAST_UPDATE_USER varchar(20) NOT NULL
);
As you can see there is
LAST_UPDATE_TIME timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
Which is not working so how can I achieve the same functionality with db2?
In DB2 9.7 for Linux, UNIX, Windows, IBM added the concept of a row change timestamp.
create table rcttest (
c1 int,
c2 char(10),
insert_ts timestamp not null with default current timestamp,
change_ts timestamp not null generated always for each row
on update as row change timestamp
);

Add default value of datetime field in SQL Server to a timestamp

I've got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn't put a timestamp in the table. I want it to enter the exact date and time that the record was entered.
I know it's in there somewhere, but I can't seem to find how to set the default value (like in Access, you use getNow() or Now()) but I don't know where to put it.
For modifying an existing column in an existing table:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
This can also be done through the SSMS GUI.
Put your table in design view (Right click on table in object explorer->Design)
Add a column to the table (or click on the column you want to update if it already exists)
In Column Properties, enter (getdate()) in Default Value or
Binding field as pictured below
In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP.
The datatype of that column may be datetime or datetime2.
e.g.
Create Table Student
(
Name varchar(50),
DateOfAddmission datetime default CURRENT_TIMESTAMP
);
While the marked answer is correct with:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
You should always be aware of timezones when adding default datetime values in to a column.
Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.
If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn
When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.
Disallow Nulls on the column and set a default on the column of getdate()
/*Deal with any existing NULLs*/
UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value
'19000101' maybe?*/
WHERE created_date IS NULL
/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL
/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
The syntax for this when creating a new table is:
CREATE TABLE MyTable
(
MYTableID INT IDENTITY(1,1),
CreateDate DATETIME NOT NULL CONSTRAINT DF_MyTable_CreateDate_GETDATE DEFAULT GETDATE()
)
This works for me...
ALTER TABLE [accounts]
ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
This also works:
CREATE TABLE Example(
...
created datetime default GETDATE()
);
Or:
ALTER TABLE EXAMPLE ADD created datetime default GETDATE();
This worked for me. I am using SQL Developer with Oracle DB:
ALTER TABLE YOUR_TABLE
ADD Date_Created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Let's say you create a database table for a registration system.
IF OBJECT_ID('dbo.registration_demo', 'U') IS NOT NULL
DROP TABLE dbo.registration_demo;
CREATE TABLE dbo.registration_demo (
id INT IDENTITY PRIMARY KEY,
name NVARCHAR(8)
);
Now a couple people register.
INSERT INTO dbo.registration_demo (name) VALUES
('John'),('Jane'),('Jeff');
Then you realize you need a timestamp for when they registered.
If this app is limited to a geographically localized region, then you can use the local server time with GETDATE(). Otherwise you should heed Tanner's consideration for the global audience with GETUTCDATE() for the default value.
Add the column with a default value in one statement like this answer.
ALTER TABLE dbo.registration_demo
ADD time_registered DATETIME DEFAULT GETUTCDATE();
Let's get another registrant and see what the data looks like.
INSERT INTO dbo.registration_demo (name) VALUES
('Julia');
SELECT * FROM dbo.registration_demo;
id name time_registered
1 John NULL
2 Jane NULL
3 Jeff NULL
4 Julia 2016-06-21 14:32:57.767
To make it simpler to follow, I will summarize the above answers:
Let`s say the table is called Customer
it has 4 columns/less or more...
you want to add a new column to the table where every time when there is insert... then that column keeps a record of the time the event happened.
Solution:
add a new column, let`s say timepurchase is the new column, to the table with data type datetime.
Then run the following alter:
ALTER TABLE Customer ADD CONSTRAINT DF_Customer DEFAULT GETDATE() FOR timePurchase
In SQLPlus while creating a table it is be like as
SQL> create table Test
( Test_ID number not null,
Test_Date date default sysdate not null );
SQL> insert into Test(id) values (1);
Test_ID Test_Date
1 08-MAR-19

Resources