I'm trying to add a constraint to a SQL Server table with the following script:
CREATE FUNCTION CheckHREmpIDRequired()
RETURNS BIT AS
BEGIN
DECLARE @ret BIT;
SET @ret = 0;
SELECT @ret = 1 WHERE EXISTS (SELECT 1 FROM GeneralSettings WHERE [Key] = 'HR_EMP_ID_REQUIRED' AND TRIM(LOWER([Value])) = 'true');
RETURN @ret;
END
GO
CREATE FUNCTION CheckHREmpIDAndDomainValid(@HREmpID varchar(10), @Domain varchar(50))
RETURNS BIT AS
BEGIN
DECLARE @required BIT;
EXEC @required = dbo.CheckHREmpIDRequired;
IF ((@HREmpID IS NULL OR TRIM(@HREmpID) = '') AND @required = 1)
BEGIN
RETURN 0
END
IF (@HREmpID IS NOT NULL AND LEN(@HREmpID) > 0)
BEGIN
DECLARE @ret BIT;
SET @ret = 0;
SELECT @ret = 1 WHERE NOT EXISTS (SELECT 1 FROM Employee WHERE HREmpID = @HREmpID AND Domain = @Domain);
RETURN @ret;
END
RETURN 1
END
GO
ALTER TABLE [dbo].[Employee]
ADD CONSTRAINT [CheckUniqueHREmpIDAndDomain] CHECK (dbo.CheckHREmpIDAndDomainValid(dbo.Employee.HREmpID, dbo.Employee.Domain) = 1);
GO
The constraint basically checks that the columns HREmpID and Domain, in combination, are unique. In the case where the HREmpID is not required and is not supplied, duplicates are allowed.
There are two functions that are called in the constraint: CheckHREmpIDAndDomainValid and CheckHREmpIDRequired. CheckHREmpIDAndDomainValid is the main function that's called from the constraint. It checks that the HREmpID and Domain combination is unique and that, if required, the HREmpID is supplied. CheckHREmpIDRequired checks whether HREmpID is required or not.
However, when I run this script, it tells me:
The ALTER TABLE statement conflicted with the CHECK constraint "CheckUniqueHREmpIDAndDomain". The conflict occurred in database "TBoardDB", table "dbo.Employee".
But all records in the Employee table are unique:
And the HREmpID is not required.
What is conflicting with the constraint? Does anyone see a problem with the script?