datetime字段上的SQL Server主键 [英] SQL Server primary key on datetime field

查看:141
本文介绍了datetime字段上的SQL Server主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL Server 2005中创建一个新表,需要2个字段:DateTime和MyValue(Int32)。 DateTime字段将是唯一的,所以我将设置一个唯一的约束。



哪个表结构更好,为什么?



MyIndex(PK,int)

MyDate(datetime)(IX_UniqueKey)

MyValue(int)





MyDate(PK,datetime)

MyValue(int)



我的感觉是,我不想在这个表中使用人造PK(MyIndex),因为它是不必要的,因为日期将是唯一的,我将使用它们来访问任何记录。但是,有一个人造PK更有效果吗?

解决方案

当你说日期是独特的,你的意思是你认为他们将是独一无二的,或者它们的唯一性是由问题的陈述保证的?根据我的经验,有些事情比一个想象的要少得多(美国社会保障号码就是一个例子)。



如果日期值不能保证唯一的,你应该添加整数键。



如果日期值保证是唯一的,它们会改变吗?如果他们改变,他们是否被其他表引用?如果两个答案是是,你可能应该添加整数键。



如果日期值被保证是唯一的,不改变或不被引用,你可以使用它们作为关键。常规DATETIME为8字节,标准INTEGER值为4字节,可能对索引影响较小。如果您的日期值只是日期,或者只是精确到分钟或更短,并且在该类型允许的更受限的范围内,您可以使用SMALLDATETIME并将这些索引值最小化为4个字节。


I'm creating a new table in SQL Server 2005 that needs 2 fields: DateTime and MyValue (Int32). The DateTime field will be unique so I will be setting a unique constraint on it.

Which table structure is better and why?

MyIndex (PK, int)
MyDate (datetime) (IX_UniqueKey)
MyValue (int)

or

MyDate (PK, datetime)
MyValue (int)

My feeling is that I don't want an artificial PK (MyIndex) in this table because it is unnecessary and because the dates will be unique I will use them to access any record. However, it may be that it's more performant to have an artificial PK...?

解决方案

When you say the dates will be unique, do you mean you think they will be unique, or their uniqueness is guaranteed by the statement of the problem? In my experience, some things turn out to be a good deal less unique than one imagines (US social security numbers being an example).

If the date values are not guaranteed unique, you should add the integer key.

If the date values are guaranteed unique, do they change? If they do change, are they referenced by other tables? If both answers are "yes" you probably should add the integer key.

If the date values are guaranteed unique, and don't change or are not referenced, you can use them for the key. Regular DATETIMEs are 8 bytes and standard INTEGER values are 4 bytes which might have a minor effect on indexing. If your date values are just dates, or only exact to the minute or less, and in the more restricted range allowed by the type, you can use SMALLDATETIME and get those index values down to 4 bytes.

这篇关于datetime字段上的SQL Server主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆