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

1

18

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?

Gravitt answered 13/12, 2010 at 5:18 Comment(0)
D
29

use:

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

Reference:

Dividend answered 13/12, 2010 at 5:19 Comment(1)
Perfect, thanks for providing the note on DATALENGTH vs LEN as well.Gravitt

© 2022 - 2024 — McMap. All rights reserved.