2011-07-08 22 views
3

我需要更新的表和列(啓用)設置爲1以下規則如何寫一個棘手的更新查詢

  1. 必須有1(永不0或> 1)記錄功能每個Employee_Guid設置爲1。
  2. 它應該選擇刪除記錄設置爲0(應該只有一個或沒有記錄,刪除設置爲0每個Employee_Guid)設置啓用爲1.
  3. 如果所有記錄已刪除設置爲1,它應該請使用最新的Create_Date_Time記錄
  4. 如果與創建日期時間相關,則可以將綁定組的任何記錄設置爲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」的問題。我想學習如何正確地做到這一點,所以我們也會讚賞類似但不解決問題的鏈接或示例。

回答

1

在這種情況下通常可以使用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 

Full example at SE Data.

+2

我以前從未見過SE數據。那件事真棒! –

0

很難回答的問題。試試這個,我希望這可以工作。

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 
)