fergus
fergus

Reputation: 75

Validate a varchar column on sql server

I would like to create a query to validate a column so that it either only allows three different entry types, i.e. "hello" "hi" or "hey" for a table called greetings, and prevents any other text from being entered. If this method is not possible is there a way to make it so that if any other text is entered like "good day" it turns into "error"

Upvotes: 0

Views: 928

Answers (1)

gotqn
gotqn

Reputation: 43666

Are you looking for a check constraint?

DROP TABLE IF EXISTS dbo.StackOverflow;
GO

CREATE TABLE dbo.StackOverflow
(
    [value] NVARCHAR(128) CONSTRAINT DF_StackOverflow_value CHECK ([value] IN ('hello', 'hi', 'hey'))
);

GO

INSERT INTO StackOverflow
VALUES ('hi');

GO

INSERT INTO StackOverflow
VALUES ('bye');

Upvotes: 7

Related Questions