Reputation: 148
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?
Upvotes: 0
Views: 1497
Reputation: 3705
I don't think you can but you have different alternatives:
EDIT: as per @a-ツ comment there are other options:
Upvotes: 3
Reputation: 5798
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?
Upvotes: -1