Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict varchar() column to specific values?

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?

like image 852
Adam Avatar asked Mar 14 '10 06:03

Adam


People also ask

How do I restrict a column value in SQL?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

How do you make a VARCHAR field unique?

In the Object Explorer under the table right-click the Indexes folder and choose New Index... . In the window that appears enter Index name: , tick the Unique checkbox and add your email field from the Add... button then click OK.

How do I limit a value in SQL?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.


2 Answers

Have you already looked at adding a check constraint on that column which would restrict values? Something like:

CREATE TABLE SomeTable (    Id int NOT NULL,    Frequency varchar(200),    CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly')) ) 
like image 54
Ashish Gupta Avatar answered Sep 22 '22 08:09

Ashish Gupta


You want a check constraint.

CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

You want something like:

ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency     CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly')) 

You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

like image 41
Michael Petrotta Avatar answered Sep 20 '22 08:09

Michael Petrotta