SQLServer:如何将固定值绑定到Column? [英] SQLServer: How To bind fixed values to Column?

查看:181
本文介绍了SQLServer:如何将固定值绑定到Column?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我定义了一个char列Type.我想严格说出它的价值,例如(黑色,白色,红色,蓝色)……

Say I defined a char column Type. I want to strict its value to say for example (Black, White, Red, Blue) Only...

我该怎么做?

我所知道的,这在Access中很容易:P

All i know, this is easy in Access :P

推荐答案

如果只有几个允许的值,则可以使用

If there are just a few permitted values then you can use a CHECK constraint:

ALTER TABLE dbo.Your_Table
ADD CONSTRAINT CK_YourTable_YourColumn
    CHECK (Your_Column IN ('Black', 'White', 'Red', 'Blue'))

如果有更多值,则可以使用查找表和 约束:

If there are more values then you can use a lookup table and a FOREIGN KEY constraint:

CREATE TABLE dbo.Lookup_Colours (Colour VARCHAR(10))
-- then populate Lookup_Colours with all permitted values

ALTER TABLE dbo.Your_Table
ADD CONSTRAINT FK_YourTable_YourColumn
    FOREIGN KEY (Your_Column)
    REFERENCES dbo.Lookup_Colours (Colour)

这篇关于SQLServer:如何将固定值绑定到Column?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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