I need to update a table and set a column (enabled) to 1 with the following rules
- There must be 1 (and never 0 or > 1) record with enabled set to 1 per Employee_Guid.
- It should choose the record that has deleted set to 0 (there should only be one or no records with deleted set to 0 per Employee_Guid) to set enabled to 1.
- If all records have deleted set to 1 it should use the record with the most recent Create_Date_Time
- If there is a tie with the create date time any record of the tieing group can be set to 1 but only one of them can be used.
If there are more than 1 record with deleted set to 0 I would like a error thrown as that is a illegal state.
Here is what I have so far
if(exists(select count(employee_guid) from Employees_M where deleted = 0 group by employee_guid having count(employee_guid) > 1))
RAISERROR('More than one record has deleted set to 0')
Update Employees_M set [ENABLE] = 0
select * into #t from employees_m where deleted = 0
insert into #t select * from employees_m where employee_guid not in (select employee_guid from #t)
and --fulfill rules 3 and 4
Update Employees_M set [ENABLE] = 1
where pk_guid in (select pk_guid from #t)
Here is the table structure
PK_Guid (primary key, uniuque, uniuqueidenitfier, not null)
Employee_Guid (uniuqueidenitfier, not null)
Deleted (bit, not null)
Enable (bit, not null)
Create_Date_Time (datetime defaults to getdate(), not null)
This is not just a “Show me teh codez” question. I want to learn how to do it correctly, so links or examples that are similar but not solving the problem would be appreciated too.
It’s often possible to use
row_numberin this scenario. Itsorder byclause allows you to assign priorities. In your case,deleted ascandCreate_Date descwould seem to capture the requirements.Here’s an example of how to use
row_numberin an update query:Full example at SE Data.