0

SQL Server 上有我的问题。我有一个命名XSGL为管理学生信息的数据库。

首先,我创建一个名为student 表IS_Student的视图。

在此处输入图像描述

CREATE VIEW IS_Student
AS SELECT sno, sname, ssex, sage
FROM student
WHERE sdept = 'IS'
WITH CHECK OPTION;

然后我想通过视图插入一个学生。

INSERT INTO IS_Student 
VALUES('200215129', '赵新', '男', 20) ;

但它有一个错误:

Msg 515, Level 16, State 2, Line 1
不能将值 NULL 插入列 'sdept',表 'XSGL.dbo.student';列不允许有 Null 值。INSERT 失败。
语句已终止。

我把它翻译成英文。

You cannot insert the value NULL into the column 'sdept', the table 'XSGL.dbo.student'; the column does not allow Null values. INSERT failed.
The statement has been terminated.

该视图IS_Student是在学生上创建的sdept'IS'我也使用WITH CHECK OPTION. 为什么错误告诉我无法将值 NULL 插入“sdept”列。

对不起我可怜的Endlish。提前致谢。

4

2 回答 2

1

条件是视图的一部分,但insert在基础表上执行。

您需要在处理视图条件的默认值的视图上创建一个插入触发器:

CREATE TRIGGER TR_Ins_IS_Student 
ON dbo.IS_Student
INSTEAD OF INSERT 
AS
BEGIN
    INSERT INTO dbo.Student (sno, sname, ssex, sage, sdept)
    SELECT sno, sname, ssex, sage, 'IS'
    FROM inserted
END
于 2020-04-22T07:45:54.090 回答
1

sdebt 不是您视图的一部分,它是基础表中不可为空的列。由于它不是您的视图或 INSERT 语句的一部分,因此它将尝试将 NULL 插入其中 - 这将使其失败。

于 2020-04-22T07:37:16.150 回答