[英]How to write a tricky update query
我需要使用以下規則更新表並將列(啟用)設置為 1
如果有超過 1 條已刪除設置為 0 的記錄,我想拋出一個錯誤,因為這是非法的 state。
這是我到目前為止所擁有的
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)
這不僅僅是一個“給我看代碼”的問題。 我想學習如何正確地做到這一點,所以類似但不能解決問題的鏈接或示例也將不勝感激。
在這種情況下,通常可以使用row_number
。 它的order by
子句允許您分配優先級。 在您的情況下, deleted asc
和Create_Date desc
似乎可以滿足要求。
以下是如何在更新查詢中使用row_number
的示例:
update emp
set enabled = case when rn = 1 then 1 else 0 end
from (
select row_number() over (partition by employee_guid
order by deleted, Create_Date desc) as rn
, *
from @employees
) emp
難以回答的問題。 試試這個,我希望這有效。
if(exists(select 1 from Employees_M where deleted = 0 having count(employee_guid) > 1))
RAISERROR('More than one record has deleted set to 0')
Update Employees_M E
set [ENABLE] = 1
WHERE EXISTS
(
SELECT 1
FROM Employees_M
WHERE E.employee_guid = employee_guid
AND (DELETED = 0 OR DELETED IS NULL)
) --SECOND POINT
OR EXISTS
(
SELECT 1
FROM Employees_M
WHERE E.employee_guid = employee_guid
AND ENABLE <> 1 -- 4 POINT
AND Create_Date_Time =
(
SELECT DISTINCT(MAX(Create_Date_Time))
FROM Employees_M
WHERE E.employee_guid = employee_guid
)
HAVING COUNT(employee_guid) = SUM(deleted) --3 POINT
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.