Samantha J T Star
Samantha J T Star

Reputation: 32788

How can I require a minimum number of characters in a column with SQL Server?

CREATE TABLE [dbo].[AdminTest] (
    [AdminTestId]  INT            IDENTITY (1, 1) NOT NULL,
    [Title]        NVARCHAR (100) NOT NULL,
    [CreatedBy]    INT            NOT NULL,
    [CreatedDate]  DATETIME       NOT NULL,
    [ModifiedBy]   INT            NOT NULL,
    [ModifiedDate] DATETIME       NOT NULL,
    [TestLevelId]  INT            NOT NULL,
    [TestStatusId] INT            NOT NULL,
    [ExamId]       INT            NOT NULL,
    [Text]         NVARCHAR (MAX) NULL,
    [Sequence]     INT            DEFAULT ((1)) NOT NULL,
    [Release]      NVARCHAR (50)  DEFAULT ((1)) NOT NULL,
    [Version]      ROWVERSION     NOT NULL,
    [Price]        MONEY          DEFAULT ((0)) NOT NULL,
    [ReleaseDate]  DATETIME       NULL,
    [Code]         VARCHAR (10)   DEFAULT (LEFT(newid(), (5))) NOT NULL
);

I set the Code column to have a default but how can I also make it so the Code column has a value that is at least 5 characters?

Upvotes: 2

Views: 5047

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300549

Create a check constraint:

ALTER TABLE AdminTest
    ADD CONSTRAINT CK_AdminTest_Code_Length CHECK (LEN(Code) >= 5);
GO

Ref: CHECK Constraints

Upvotes: 5

Related Questions