I'm writing a very simple blog engine for own use (since every blog engine I encountered is too complex). I want to be able to uniquely identify each post by its URL which is something like /2009/03/05/my-blog-post-slug
. To accomplish it in the data tier, I want to create a compound unique constraint on (Date, Slug)
where Date
is only the date part (ignoring the time of day) of the composition date. I have a few ideas myself (like another column, probably calculated, to hold only the date part) but I came to SO to know what's the best practice to solve this problem.
I doubt SQL Server version matters here, but for the records, I'm on 2008 Express (I appreciate a more portable solution).
Table schema:
create table Entries (
Identifier int not null identity,
CompositionDate datetime not null default getdate(),
Slug varchar(128) not null default '',
Title nvarchar(max) not null default '',
ShortBody nvarchar(max) not null default '',
Body nvarchar(max) not null default '',
FeedbackState tinyint not null default 0,
constraint pk_Entries primary key(Identifier),
constraint uk_Entries unique (Date, Slug) -- the subject of the question
)
Selected Solution:
I think marc's solution is more appropriate, considering this question is about 2008. However, I'll go with the integer method (but not with INSERT
s, as it does not ensure the integrity of data; I'll use a precomputed integer column) since I think it's easier to work with the integer thing from the client (in the query).
Thank you guys.
create table Entries (
Identifier int not null identity,
CompositionDate smalldatetime not null default getdate(),
CompositionDateStamp as cast(year(CompositionDate) * 10000 + month(CompositionDate) * 100 + day(CompositionDate) as int) persisted,
Slug varchar(128) not null default '',
Title nvarchar(max) not null default '',
ShortBody nvarchar(max) not null default '',
Body nvarchar(max) not null default '',
FeedbackState tinyint not null default 0,
constraint pk_Entries primary key(Identifier),
constraint uk_Entries unique (CompositionDateStamp, Slug)
)
go