Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLServer: How To bind fixed values to Column?

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

like image 325
Shankarooni Avatar asked Dec 17 '22 08:12

Shankarooni


2 Answers

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)
like image 198
LukeH Avatar answered Jan 04 '23 19:01

LukeH


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:

ALTER TABLE MyTable
ADD CONSTRAINT CK_MyTable_ColorType
    CHECK (ColorType IN ('Black', 'White', 'Red', 'Blue'))

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.

SELECT *
FROM   MyTable INNER JOIN
         ColorTable ON MyTable.ColorID = ColorTable.ID

Updated: With Constraint instead of Rule older Databases can still use Rules though (2000).

CREATE RULE Color_Rule
AS 
@list IN ('Black', 'White', 'Red', 'Blue')

Hope it helps

like image 20
Jesper Fyhr Knudsen Avatar answered Jan 04 '23 18:01

Jesper Fyhr Knudsen