How to create a unique constraint just on the date part of a datetime?

淺唱寂寞╮ 提交于 2019-11-30 12:41:40

Well, in SQL Server 2008, there's a new datatype called "DATE" - you could use that column and create an index on that.

You could of course also add a computed column of type "DATE" to your table and just fill the date portion of the DATETIME column into that computed column, make it PERSISTED, and index it. Should work just fine!

Something like that:

ALTER TABLE dbo.Entries
   ADD DateOnly as CAST(CompositionDate AS DATE) PERSISTED

CREATE UNIQUE INDEX UX_Entries ON Entries(DateOnly, Slug)

Marc

Since you're on 2008, use the Date datatype as Marc suggests. Otherwise, an easier solution is to have a non-computed column (which means you'll have to populate it on an INSERT) which uses the date in the format YYYYMMDD. That's an integer data type and is small and easy to use.

For SQL 2005, you could do essentially the same thing that marc_s recommended, just use a standard DateTime. It would look something like this (untested code here):

ALTER TABLE Entries ADD
    JustTheDate AS DATEADD(day, DATEDIFF(day, 0, CompositionDate), 0) NOT NULL PERSISTED

Then create your index on (JustTheDate, Slug)

Note: The DATEADD/DATEDIFF statement there calculates just the date of the CompositionDate .

Over the years we've had a variety of problems with Computed Columns in SQL Server, so we've stopped using them.

You could use a VIEW with a column for date-only - and put a unique index on that VIEW's column.

(A possibly useful side-effect is that you can have the VIEW exclude some rows - so you could implement things like "DateColumn must be unique, but exclude WHERE DateColumn IS NULL)

The existing CompositionDate column could be split into two fields - CompositionDate and CompositionTime - and a Retrieve View that joins them back together if you need that - which would then allow a native index on the Date-only column

(This can be implemented in SQL 2005 and earlier using DateTime - although slightly extravagant for just the Date or Time, and not both)

And lastly you could have an INSERT / UPDATE trigger that enforced that no other record existed with a duplicate CompositionDate (date part only)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!