question

SimonMeduka avatar image
SimonMeduka asked

I need a check constraint - sql server

employee can never be her own manager. I need a constraint on the dbo.Employees to prevent this create dbo.Employees( EmpId INT primary key identity, MgrId INT , FullName NVARCHAR(50)) MgrId for general manager is NULL , REST MANAGER NUMBERS 1,2,3,4 etc ALTER TABLE dbo.Employees ADD CONSTRAINT CK_NULLforGeneralManager CHECK( 'can't figure it out')
sql-server-2012constraint
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Magnus Ahlkvist avatar image
Magnus Ahlkvist answered
How about this? ALTER TABLE dbo.Employees ADD CONSTRAINT CK_ManagerIsNotSelf CHECK (EmpId MgrId); I would also add a self referencing Foreign Key, to ensure that no Employee has a non existing employee as manager. ALTER TABLE dbo.Employees ADD CONSTRAINT FK_EmployeeManager FOREIGN KEY (MgrId) REFERENCES dbo.Employees(EmpId);
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

SimonMeduka avatar image SimonMeduka commented ·
Thank you so much! I am new to sql and looks so easy and simple.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.