Question

I have the following:

create table dbo.Users
(
  Id int identity not null 
    constraint PK_Users_Id primary key clustered (Id),  
  Email nvarchar (120) not null
    constraint UQ_Users_Email unique (Email),
  Username nvarchar (120) not null
    constraint UQ_Users_Username unique (Username)
);

Can I set a constraint to make Email and Username equal?

Thank You, Miguel

Was it helpful?

Solution

Below is the appropriate SQL to address the question directly:

create table dbo.Users
(
  Id int identity not null 
    constraint PK_Users_Id primary key clustered (Id),  
  Email nvarchar (120) not null
    constraint UQ_Users_Email unique (Email),
  Username nvarchar (120) not null
    constraint UQ_Users_Username unique (Username)      
);


alter table dbo.Users add constraint CK_EmailEqualsUsername
check (username = email)

A, most likely better, more common approach would be to perform the comparison somewhere higher in the call stack (different layer e.g.: Presentation Layer/Domain Layer/Service Layer)

OTHER TIPS

Try this code:

alter table dbo.Users
add constraint ck_us check(Email=Username)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top