我正在使用microsoft sql server和我学习sql的基础... 我有一张桌子,里面有患者姓名和他们的主要医生。 我想检查一下医生不能成为超过4名患者的主要医生 这是我尝试过的:
CREATE ASSERTION assertion12
(not exist(
select DOCTOR.SSN
from Patient, DOCTOR
where Patient.primaryDoctor_SSN = DOCTOR.SSN
group by DOCTOR.SSN
having count(primaryDoctor_SSN) >= 5
);
但我在第一行收到错误:"找不到存储过程" 。 (实际上红线是" CREATE"并显示此消息)
我该怎么办?!我查了一些网站,我看到写作断言就像我做的那样,我不知道为什么会出现这个错误。
答案 0 :(得分:2)
SQL Server不支持CREATE ASSERTION
。
事实上,当前的SQL产品没有正确支持CREATE ASSERTION
。 Sybase SQL Anywhere支持它,但据报道存在允许有时违反约束的问题。 Rdb在被DEC监督时显然支持它(显然在SQL标准的早期有影响力,可能是CREATE ASSERTION
首先在标准中的原因)但该产品不再是。
STOP PRESS:according to their documentation,HyperSQL(HSQLDB)支持断言(虽然我想知道他们为什么不在their list of features上大喊大叫)。
参考 Does SQL Server 2008 support the CREATE ASSERTION syntax?
答案 1 :(得分:1)
SQL Server不支持Create Assertion
,您可以使用Check Constraint或Create Trigger作为:
IF OBJECT_ID ('assertion12','TR') IS NOT NULL
DROP TRIGGER assertion12;
GO
-- This trigger prevents a row from being inserted in the Patients table
-- when current patient's primary doctor already has patients = 4 (max 4)
CREATE TRIGGER assertion12 ON Patient
AFTER INSERT
AS
IF EXISTS ( select count(P.primaryDoctor_SSN)
from Patient P
JOIN inserted AS i
ON p.primaryDoctor_SSN = i.primaryDoctor_SSN
group by P.primaryDoctor_SSN
having count(P.primaryDoctor_SSN) =4
)
BEGIN
RAISERROR ('Primary Doctor Assigned to the Patient already has 4 patients.', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;
GO
-- This statement attempts to insert a row into the Patient table
-- The AFTER INSERT trigger is fired and the INSERT transaction is rolled back.
INSERT INTO Patient values (5,1)
GO