2014-11-15 44 views
1

我有3個表tblteamtblaccounttbluser有以下的列:軟刪除使用SQL Server存儲過程

tblTeam

(TeamId int, 
TeamName varchar(20), 
IsDeleted bit) 

tblUser

(UserId int, 
UserName varchar(20), 
TeamId int) 

tblAccount

(AccountId int, 
AccountName varchar(20), 
TeamId int, 
UserId int 
) 

我想要做什麼是我想要更新1

刪除列爲此,我曾嘗試

Create procedure sp_isdeleted(
    @pteamid int 
As 
Begin 
    Update tblTeam 
    set IsDeleted = 1 
    Where TeamId = @pteamid 
End 

但我想,如果團隊與任何用戶相關聯或帳戶和任何用戶仍然在隊Isdeleted仍然是0.

我該如何檢查這種情況?請幫忙。

+3

備註:您應該**不要**爲存儲過程使用'sp_'前綴。微軟已經保留了這個前綴以供自己使用(參見*命名存儲過程*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),以及你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也是不利的](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! –

+0

@marc_c好吧我會用不同的前綴。非常感謝你回答 – Felixerity

回答

2

試試這個update語句的SP內部:

Update t 
set t.IsDeleted = 1 
from tblTeam t 
where t.TeamId = @pteamid 
and not exists (select 1 from tblUser where TeamId = @pteamid) 
and not exists (select 1 from tblAcount where TeamId = @pteamid) 
+0

如果其他條件可以在這裏適用所以如何駕駛室ne如果其他條件 – Felixerity

+0

我不明白..什麼是真正的問題?你能用其他的話來提問嗎? –

+0

對不起,但仍不明白的問題:)「bem」是什麼意思? –

1

如果你把邏輯放到一個地方,或者很多地方,還有就是軟刪除可以從別的地方來執行的可能性。你想讓任何時候都無法在任何地方進行刪除。如果系統執行軟刪除時的默認FK限制(不能刪除一行,如果有FK指向它的話),就像硬刪除一樣嗎?說,有一個想法!而且它的實現非常簡單。

只需製作表格PK的刪除標誌部分(或者更好的方法是將其與PK一起添加到唯一索引中)。然後,每個FK to Team在該字段中使用0值。如果有任何引用該團隊的FK,則任何試圖修改IsDeleted字段的嘗試都將被阻止。

這是從內存中,以便語法可能是前途未卜:

create table Teams(
    ID  int not null, 
    IsDeleted bit not null default 0, 
    ... 
    constraint PK_Teams primary key(ID) 
); 
create unique index UQ_Team_ID_IsDeleted on Team(ID, IsDeleted); 

create table AllOthers(
    ... 
    TeamID   int, 
    TeamStillThere bit, 
    ... 
    constraint CK_TeamStillThere check IsNull(TeamStillThere, 0) = 0; 
    constraint FK_AllOthers_Teams foreign key(TeamID, TeamStillThere) 
     references Teams(ID, IsDeleted); 
); 

注意,FK,只能是指未刪除的團隊,一旦建立連接,球隊無法刪除(硬或軟)。另外,如果參考團隊不關心團隊是否被刪除,您仍然可以定義FK參考,例如團隊的歷史記錄。無論哪種方式,都要讓系統儘可能地完成所有工作。