Jackson Tai
Jackson Tai

Reputation: 493

How to create constraint for specific characters in sql server?

I was trying to create a constraint for the book ID that the remaining 3 characters after BID must be 001 until 999. What can I do instead of using % ?

CREATE TABLE Book
(
    [Book ID] CHAR(6),
    [Title] VARCHAR(50) NOT NULL,
    [Genre] VARCHAR(50) NOT NULL,
    [Author] VARCHAR(50) NOT NULL,
    [Price] DECIMAL(18,2) NOT NULL,
    CONSTRAINT Book_PK PRIMARY KEY ([Book ID]),
    CONSTRAINT chk_BookID  CHECK ([Book ID] like 'BID%'),
);

Upvotes: 2

Views: 1343

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269643

SQL Server supports characters classes in LIKE:

CONSTRAINT chk_BookID  CHECK ([Book ID] like 'BID[0-9][0-9][0-9]')

Note: I would recommend that you rename the column to Book_ID or BookID. Having spaces in column names just clutters queries.

Upvotes: 1

Related Questions