2

I'm new in SQL and I need to create table with specified field format. How to add CHECK condition that will assure that input will be formatted e.g.

[LLLDD]

where L is a letter and D is a digit?

3 Answers 3

3

Try this if you are adding the constraint on a new table

CONSTRAINT ck_data_checker CHECK ([columnName] LIKE ('[A-Z][A-Z][A-Z][0-9][0-9]'))

Try this if you are adding the constraint on existing table

  ALTER TABLE tableName
  ADD CONSTRAINT ck_data_checker CHECK ([columnName] LIKE ('[A-Z][A-Z][A-Z][0-9][0-9]'))
Sign up to request clarification or add additional context in comments.

Comments

1

Try this: http://sqlfiddle.com/#!6/3974b

create table test (
  field1 char(5),
  check (field1 like '[a-z][a-z][a-z][0-9][0-9]')
);

insert into test values ('ttt09'); --this will succeed

If you were to change the insert to:

insert into test values ('testi'); -- this will fail
insert into test values ('12345'); -- this will fail

Comments

0

I'm no sql server expert, but I think you can add a LIKE with a regular expression. Have a look at these websites

https://msdn.microsoft.com/en-us/library/ms179859.aspx

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/dc127433-2982-4065-b290-f411a075a694/use-regular-expressions-to-check-sql-server-2012-table-fields?forum=databasedesign

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.