Lista de valores predeterminados de SQL Server

How do I create a list of default values in a SQL Server 2008 R2 column? I want a column to have the default values of easy, medium, expert.

preguntado el 08 de enero de 11 a las 17:01

What do you mean by "default values"? Allowable values, like MySQL ENUMs? -

2 Respuestas

An an example, imagine a table of different math tests with a difficulty rating which must be either 'easy', 'medium' or 'expert'

CREATE TABLE Test
(
    MathTestID smallint NOT NULL,
    DifficultyRating varchar(6) NOT NULL,
    CHECK (DifficultyRating In ('Easy', 'Medium','Expert'))
)

INSERT INTO Test
VALUES (1, 'Easy') //Works...

INSERT INTO Test
VALUES (1, 'Medium') //Works...

INSERT INTO Test
VALUES (1, 'Expert') //Works...

INSERT INTO Test
VALUES (1, 'Genius') //Fails...INSERT statement conflicted with CHECK constraint

Respondido el 08 de enero de 11 a las 20:01

Thanks! I was looking at that, but didn't know how to implement it. Again thank you very much! - user568171

Unlike MySql, SQL Server doesn't have enum types that you can constrain a column with ease.

The closest you can come is use a CHECK restricción.

Respondido el 08 de enero de 11 a las 20:01

Other than "but it automagically makes those nice little dropdowns in PHPMyAdmin" I don't see that much actual benefit in ENUM anyway. - Tomalak

@Tomalak - Agreed. I would normally simply use a lookup table and FK constraint. - Oded

Yes. That would also lead to "no structural database changes necessary to allow another value", which in turn leads to "unprivileged account (i.e. web server) can add new values", among other things, like being better-suited for i18n or indexing (and "free choice of the underlying data type and value", of course). - Tomalak

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.