gpt4 book ai didi

sql - 如何仅在日期时间的日期部分创建唯一约束?

转载 作者:行者123 更新时间:2023-12-02 10:06:45 26 4
gpt4 key购买 nike

我正在编写一个非常简单的博客引擎供自己使用(因为我遇到的每个博客引擎都太复杂)。我希望能够通过 URL 来唯一标识每个帖子,例如 /2009/03/05/my-blog-post-slug。为了在数据层中完成它,我想在 (Date, Slug) 上创建一个复合唯一约束,其中 Date 只是日期部分(忽略一天中的时间)组成日期。我自己有一些想法(就像另一列,可能是经过计算的,只保留日期部分),但我来到这里是为了知道解决这个问题的最佳实践是什么。

我怀疑 SQL Server 版本在这里很重要,但为了记录,我使用的是 2008 Express(我欣赏更便携的解决方案)。

表架构:

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
)

选择的解决方案:

考虑到这个问题是关于 2008 年的,我认为 marc 的解决方案更合适。但是,我将使用整数方法(但不使用 INSERT,因为它不能确保数据;我将使用预先计算的整数列),因为我认为使用客户端(在查询中)的整数更容易。

谢谢大家。

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

最佳答案

在 SQL Server 2008 中,有一种名为“DATE”的新数据类型 - 您可以使用该列并在其上创建索引。

您当然也可以将“DATE”类型的计算列添加到表中,然后将 DATETIME 列的日期部分填充到该计算列中,使其持久化并为其建立索引。应该可以正常工作!

类似的事情:

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

CREATE UNIQUE INDEX UX_Entries ON Entries(DateOnly, Slug)

马克

关于sql - 如何仅在日期时间的日期部分创建唯一约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/620561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com