2015-01-16 128 views
2

我有這個表:防止單列刪除與觸發

CREATE TABLE Workspaces (
AreaNr CHAR(2) 
    CONSTRAINT ck_a_areanr REFERENCES Areas(AreaNr) 
    ON DELETE CASCADE 
    ON UPDATE NO ACTION, 
SpaceNr INT 
    CONSTRAINT ck_spacenr CHECK (SpaceNr > 0 AND SpaceNr < 1001), 
Area DECIMAL(2,1) 
    CONSTRAINT ck_areal CHECK (area > 0), 
CONSTRAINT ck_workspaces PRIMARY KEY (AreaNr, SpaceNr) 
) 

現在我想創建一個觸發器,以防止刪除從表工作區單行(隨機選擇)。此刻我有以下觸發器,但此觸發器仍允許刪除單行。

當前觸發:

CREATE TRIGGER deleteWorkspace ON Workspaces 
FOR DELETE AS 

BEGIN 
DECLARE @Count int 
SET @Count = @@ROWCOUNT; 

IF @Count >= (SELECT SUM(row_count) 
FROM sys.dm_db_partition_stats 
WHERE OBJECT_ID = OBJECT_ID('Workspaces') AND index_id = 1 
) 

BEGIN 
RAISERROR('You cannot delete all rows from Workspaces!',16,1) 
ROLLBACK TRANSACTION 
RETURN; 
END 

END 
GO 

期望的結果:我希望能夠防止刪除上面的表中的一行,我將非常感激,如果有人能夠幫助我改變上面的觸發器,這樣可以修復。有誰知道這可以做到嗎?

回答

3

你會想在這個實例中使用已刪除的虛擬表。我不完全知道爲什麼你只關心行刪除,但這裏是代碼:

CREATE TRIGGER deleteWorkspace ON Workspaces 
FOR DELETE AS 

IF(SELECT COUNT(*) FROM deleted) = 1 
BEGIN 
RAISERROR('Single Delete Not Allowed!', 16, 1) 
ROLLBACK 
END 
ELSE 
RAISERROR('Multiple Rows Being Deleted, Allowed!', 16, 1) 
BEGIN 
END 

END 
GO 

-Sean

+0

謝謝你,是沒有的伎倆! :) – eqinna

+1

由於某些原因,我不得不使用以下格式來交換RAISEERROR(SQL 2012)'THROW 51000,'不允許刪除',1;' – DarrenMB