SQLServer:如何将固定值绑定到列?
假设我定义了一个 char 列类型。 我想严格限制它的值,例如(黑、白、红、蓝)……
我该怎么做?
据我所知,这在 Access 中很容易:P
Say I defined a char column Type. I want to strict its value to say for example (Black, White, Red, Blue) Only...
How can I do that??
All i know, this is easy in Access :P
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果只有几个允许的值,那么您可以使用
CHECK 约束
:
如果有更多值,则可以使用查找表和
FOREIGN KEY
约束:If there are just a few permitted values then you can use a
CHECK
constraint:If there are more values then you can use a lookup table and a
FOREIGN KEY
constraint:您应该使用规则(正如所指出的,规则现已弃用,而应使用约束)或包含您允许的颜色的颜色表的外键。
检查约束可以这样创建:
如果您想使用表,那么您应该创建一个带有 colorName 和 ID 的“颜色”表。 在需要引用的表上,您应该将带有外键的列添加到“颜色”表 ID。
要引用“颜色”表,您必须使用连接,例如
更新:使用约束而不是规则,但较旧的数据库仍然可以使用规则(2000)。
希望能帮助到你
You should either use a Rule (as was pointed out Rules are now deprecated instead constraints should be used) or a foreign key to a Color table containing the Colors you allow.
A Check constraint can be created like this:
If you want to go with a table, then you should create a 'Color' table with the colorName and an ID. On the table(s) that need the reference you should add a column with the foreign key to the 'Color'-table ID.
To reference the 'Color'-table you have to use a join e.g.
Updated: With Constraint instead of Rule older Databases can still use Rules though (2000).
Hope it helps
一种方法是创建一个单独的表“类型”并将您的值放在那里。 过去具有 varchar 类型的表现在将具有指向另一个表的 FK TypeID。
这将需要额外的连接,但可以让您控制哪些字符串可以是类型。
One way to do this would be to create a separate table "Type" and put your values there. The table that use to have the Type varchar, would now have a FK TypeID that points to the other table.
This will require an extra join, but will give you control over what strings can be Types.
您需要列规则
是的,就像访问一样简单。
You need a rule on the column
And yes , it's as easy as it is in access.