SQL 约束:特定键每天只能有一条记录
有没有一种方法可以创建约束或某种方式,让 FK 列一天只能有一条记录? IE
PK(IDENTITY(1,1)) FK_FIELD DATETIME
------------------------------
1 1 2012-02-22 4:50 p.m.
2 2 2012-02-23 12:00 p.m.
3 2 2012-02-23 9:00 p.m. -- This one should not be allowed because the FK_Field 2 would have 2 record in one day.
4 1 2012-02-23 08:00 a.m
希望有人理解我想要实现的目标。
提前致谢。
There is a way to create a constraint or something where I can have only one record for a Day for a FK column? I.E.
PK(IDENTITY(1,1)) FK_FIELD DATETIME
------------------------------
1 1 2012-02-22 4:50 p.m.
2 2 2012-02-23 12:00 p.m.
3 2 2012-02-23 9:00 p.m. -- This one should not be allowed because the FK_Field 2 would have 2 record in one day.
4 1 2012-02-23 08:00 a.m
Hopefully someone understand what im trying to archieve.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
考虑使用:
各种持久列的一些示例(非常感谢 Aaron Bertrand):
2008这些例子是经过仔细选择的,以确保功能确定性。
下面是一个 SQL 示例:
如果您尝试插入,您将得到以下结果:
SQL Server Management Studio 中显示的消息是:
Consider using:
Some examples of a variety of persisted columns (Much thanks to Aaron Bertrand):
N.B. These examples were chosen carefully to ensure function determinism.
Here's a sample SQL:
If you attempted the INSERTs, this is what you get:
The message shown in SQL Server Management Studio is:
您可以创建一个检查约束,该约束使用用户定义的函数来检查整个表中是否存在今天的条目。
you can create a check constraint that uses a user defined function that checks the whole table for an existence of a todays entry.
这是一种方法
您还可以使用约束,正如亚伦建议的那样
然后在键和计算字段上创建唯一索引
Here is one approach
You can also use a constraint, as Aaron suggested
Then create a unique index on the key and that computed field
我会尝试在数据库的两个不同字段中或按组合将日期与时间分开。然后我会在日期上添加一个唯一的约束。只要该日期位于您添加约束的列中,以下内容就会阻止对同一日期进行任何输入。
还有一个非常有趣的线程,您应该检查这里解决的类似问题 如何仅在日期时间的日期部分创建唯一约束?
希望这有帮助
I would try to separate the date from the time either in 2 different fields of the database or by composition. Then I would add a unique constraint on the date. The following would prevent any entry to be made for a same date as long as only the date is in the collumn you add the constraint to.
There is also a quite interesting thread you should check with a similar problem that was solved here How to create a unique constraint just on the date part of a datetime?
Hope this helps