我需要更新的表和列(啓用)設置爲1以下規則如何寫一個棘手的更新查詢
- 必須有1(永不0或> 1)記錄功能每個Employee_Guid設置爲1。
- 它應該選擇刪除記錄設置爲0(應該只有一個或沒有記錄,刪除設置爲0每個Employee_Guid)設置啓用爲1.
- 如果所有記錄已刪除設置爲1,它應該請使用最新的Create_Date_Time記錄
- 如果與創建日期時間相關,則可以將綁定組的任何記錄設置爲1,但只能使用其中的一個記錄。
如果有超過1條記錄被刪除設置爲0我想拋出一個錯誤,因爲這是一個非法的狀態。
這裏是我迄今爲止
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)
這裏是表結構
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)
這不只是一場「秀我德codez」的問題。我想學習如何正確地做到這一點,所以我們也會讚賞類似但不解決問題的鏈接或示例。
我以前從未見過SE數據。那件事真棒! –