假设我们有一个名为StudentAccount
的表格,其中包含SID
列(学生ID)和AmountOwing
。
我们无法从系统中删除该帐户,除非学生在其帐户中没有任何欠款。 (那是AmountOwing = $0.00
)。
例如,表格可能如下:
SID | Amount Owing
-------+--------------
32415 | $30.00
39872 | $0.00
35135 | $3200.00
在这种情况下,我们只能删除第2行。
有没有办法使用有效的MS SQL Server 2012 SQL语法对表强制执行此约束(以便未受过教育的用户不会意外删除非空帐户)?
答案 0 :(得分:3)
试试这个:
CREATE TRIGGER trgD_StudentAccount_Delete
ON dbo.StudentAccount
INSTEAD OF DELETE
AS
BEGIN
IF EXISTS (
SELECT *
FROM deleted d
WHERE d.AmountOwing <> 0
)
BEGIN
ROLLBACK;
RAISERROR('Delete error: there are students with Amount <> 0', 16, 1);
END
ELSE
BEGIN
DELETE StudentAccount
WHERE EXISTS( SELECT * FROM deleted d WHERE d.[SID] = StudentAccount.[SID] )
END
END
答案 1 :(得分:-1)
建议您将AmountOwing作为数字值(int,float,...)
DELETE
FROM StudentAccount
WHERE AmountOwing > 0
或使用触发器(以便用户不应删除任何内容)
CREATE TRIGGER DML_ON_TABLEA
ON StudentAccount
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
CASE
WHEN (AmountOwing = 0) THEN
-- DELETE STATEMENT
END
END
GO