编写约束以强制至少出现 1 次值

writing a constraint to enforce a minimum 1 occurence af a value

我正在尝试编写检查约束以强制在 a table:

中至少出现 1 个值
DECLARE @Instances INT
SELECT @Instances = COUNT (instructor) FROM Prof_Teach_Courses
SET @Instances =  (SELECT COUNT(instructor) FROM Prof_Teach_Courses)
GO
ALTER TABLE Prof_Teach_Courses
ADD CONSTRAINT count_1_instance CHECK (@Instances >= 1)
GO

我遇到一个错误:

Must declare the scalar variable "@Instances".

你不能用变量解决这个问题你需要一个函数

CREATE TABLE Prof_Teach_Courses (col1 int, instructor int);  
GO
CREATE FUNCTION CheckInstructor()  
RETURNS int  
AS   
BEGIN  
   DECLARE @Instances int  
   SELECT @Instances = COUNT(instructor) FROM Prof_Teach_Courses 
   RETURN @Instances  
END;  
GO
ALTER TABLE Prof_Teach_Courses  
ADD CONSTRAINT count_1_instance CHECK (dbo.CheckInstructor() >= 1 );  
 
GO

db<>fiddle here