SQL Server - Add Constraint for existing table using Alter Table function

3.6k views Asked by At

I got a little trouble with SQL. This is the table Customers :

ID      Name     Address                Phone
KP001   Bill     Jl Bali NO 27          81976524451
KP002   Jane     Jl Sandang NO 5        81876537521
KP003   Dion     Jl Kebon Jeruk NO 7    81684234913

the original structure table Customer :

CREATE TABLE Customer
(
ID char(5)primary key not null,
Name varchar(20),
Address varchar(30),
Phone varchar(12),
constraint cs2 check (LEN(ID)=5),
constraint cs3 check (ID like 'KP[0-9][0-9][0-9]'),
)

and I want to change table structure using Alter Table. I want to Add constraint to table Customers which Address after the 'no' must be a number.

First, in Indonesia there are street names using the 'NO' as an indicator street number. And requires the Customer table after the 'NO' is a number. I've tried with this query :

ALTER TABLE Customers WITH NOCHECK
ADD CONSTRAINT cs_address 
CHECK (CHARINDEX('no',Address)>1 AND
ISNUMERIC ( SUBSTRING (Address,7,2)) =1)

I know the query incorrect, but can you help me to fix the error and get the right results?

*sorry if my english is not good

1

There are 1 answers

6
Vikdor On

If you are looking to validate the Address to always start with NO, followed by a numeric value, then

ALTER TABLE Customers WITH NOCHECK
ADD CONSTRAINT cs_address
CHECK
(
        CHARINDEX('no', Address) >= 1 
    AND ISNUMERIC(LTRIM(RTRIM
                (SUBSTRING (Address, CHARINDEX('no', Address) + 2, 7)))) = 1
)