Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a CHECK constraint on a VARCHAR column in SQL Server specifying a minimum data length?

I have a VARCHAR(30) column in a Microsoft SQL Server database. I'd like to add a CHECK constraint that does not allow a value in the column to be less than 3 characters. What is the expression I must use?

like image 661
Jake Petroules Avatar asked Dec 13 '10 05:12

Jake Petroules


People also ask

Can check constraint be specified in column level?

You can define CHECK constraints at the column level, where the constraint applies only to a single column, and at the table level. You can also add CHECK constraints to a table using ADD CONSTRAINT .

How do I add a check constraint to an existing column in SQL Server?

The syntax for creating a check constraint in an ALTER TABLE statement in SQL Server (Transact-SQL) is: ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (column_name condition); table_name.

What is the limit of check constraints on a column?

Microsoft recommends no more than 253 foreign key constraints per column, though you are only limited by the number of objects in a database (2,147,483,647).

How can check column constraint in SQL Server?

Discussion: Use the view table_constraints in the information_schema schema. The column table_name gives you the name of the table in which the constraint is defined, and the column constraint_name contains the name of the constraint.


1 Answers

use:

ALTER TABLE [dbo].[YOUR_TABLE]
ADD CONSTRAINT [MinLengthConstraint] CHECK (DATALENGTH([your_column]) > 2)

Reference:

  • DATALENGTH vs LEN
  • SQL SERVER – 2005 Constraint on VARCHAR(MAX) Field To Limit It Certain Length
like image 123
OMG Ponies Avatar answered Sep 19 '22 11:09

OMG Ponies