/* EmployeeNoUnique_DB_Changes.sql Why: dbo.EMPLOYEE.EMPLOYEENO had no uniqueness guard, so two employees could be saved with the same Employee No (bulk upload, manual entry, ESS lookups by number all assume it is unique). What: Adds unique constraint UQ_EMPLOYEE_EMPLOYEENO on dbo.EMPLOYEE (EMPLOYEENO). Stops with an error (and changes nothing) if duplicate Employee Nos already exist - fix those first with the query printed below. Run order: Any time; no code depends on it. Re-runnable: does nothing when the constraint exists. */ IF EXISTS (SELECT 1 FROM sys.objects WHERE name = 'UQ_EMPLOYEE_EMPLOYEENO' AND parent_object_id = OBJECT_ID('dbo.EMPLOYEE')) PRINT 'UQ_EMPLOYEE_EMPLOYEENO already exists - nothing to do.'; ELSE IF EXISTS (SELECT EMPLOYEENO FROM dbo.EMPLOYEE GROUP BY EMPLOYEENO HAVING COUNT(*) > 1) BEGIN RAISERROR('Duplicate EMPLOYEENO values exist. Find them with: SELECT EMPLOYEENO, COUNT(*) FROM dbo.EMPLOYEE GROUP BY EMPLOYEENO HAVING COUNT(*) > 1', 16, 1); END ELSE BEGIN ALTER TABLE dbo.EMPLOYEE ADD CONSTRAINT UQ_EMPLOYEE_EMPLOYEENO UNIQUE NONCLUSTERED (EMPLOYEENO); PRINT 'UQ_EMPLOYEE_EMPLOYEENO added.'; END GO