簡體   English   中英

如何編寫一個棘手的更新查詢

[英]How to write a tricky update query

我需要使用以下規則更新表並將列(啟用)設置為 1

  1. 每個 Employee_Guid 必須有 1 個(並且永遠不會是 0 或 > 1)記錄啟用設置為 1。
  2. 它應該選擇已刪除設置為 0 的記錄(每個 Employee_Guid 應該只有一條或沒有已刪除設置為 0 的記錄)將啟用設置為 1。
  3. 如果所有記錄都已刪除設置為 1,則應使用具有最近 Create_Date_Time 的記錄
  4. 如果與創建日期時間有關聯,則關聯組的任何記錄都可以設置為 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 ascCreate_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

SE Data 的完整示例。

難以回答的問題。 試試這個,我希望這有效。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM