将 varchar() 列限制为特定值?
有没有办法为 MS SQL Server 2008 中的 varchar 列指定 4 个不同的值?
例如,我需要一个名为Frequency (varchar) 的列,该列仅接受“每日”、“每周”、“每月”、“每年”作为可能值。
创建表时是否可以在 SQL Server Management Studio 中设置?
Is there a way to specify, for example 4 distinct values for a varchar column in MS SQL Server 2008?
For example, I need a column called Frequency (varchar) that only accepts 'Daily', 'Weekly', 'Monthly', 'Yearly' as possible values
Is this possible to set within the SQL Server Management Studio when creating the table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否已经考虑过在该列上添加一个
检查约束
来限制值?像这样的东西:Have you already looked at adding a
check constraint
on that column which would restrict values? Something like:您需要一个检查约束。
您想要类似的东西:
您还可以使用标量函数实现检查约束,如上面的链接中所述,这就是我更喜欢的方式。
You want a check constraint.
You want something like:
You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.
就个人而言,我将其编码为tinyint并且:
原因:
平均需要8个字节来存储文本,tinyint 为 1 个字节。对于数百万行,这将产生影响。
整理怎么样? “每日”和“每日”一样吗?进行这种比较需要资源。
最后,如果您想添加“双周”或“每小时”怎么办?当您只需向查找表添加新行时,这需要更改架构。
Personally, I'd code it as tinyint and:
Reasons:
It will take on average 8 bytes to store text, 1 byte for tinyint. Over millions of rows, this will make a difference.
What about collation? Is "Daily" the same as "DAILY"? It takes resources to do this kind of comparison.
Finally, what if you want to add "Biweekly" or "Hourly"? This requires a schema change when you could just add new rows to a lookup table.
当您编辑表格时
右键单击->检查约束->添加->在表达式字段中输入类似
Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly')
的内容,并在 (Name) 字段中输入一个合适的约束名称。你完成了。
When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like
Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly')
in expression field and a good constraint name in (Name) field.You are done.