SQL Server 如何使用存储过程向表中插入值[已关闭]

gwo2fgha  于 2023-01-01  发布在  其他
关注(0)|答案(1)|浏览(187)

这个问题似乎与help center中定义的范围内的编程无关。
11小时前关门了。
Improve this question
我有这些表:
级别

[GradeId] [int] NOT NULL,
[Grade] [int] NOT NULL,
[ExamDate] [date] NULL,
[ProfessorId] [int] NOT NULL,
[SubjectId] [int] NOT NULL,
[StudentId] [int] NOT NULL,
[Active] [bit] NOT NULL,)

以及
学生

[StudentId] [int] NOT NULL,
    [FirstName] [nvarchar](50) NOT NULL,
    [LastName] [nvarchar](50) NOT NULL,
    [Email] [varchar](50) NULL,
    [Active] [bit] NOT NULL,
    [CNP] [nvarchar](50) NOT NULL,
    [GroupId] [int] NOT NULL,

我想在Grade表中插入一个成绩,student id对应Student表中的一个学生。在插入成绩之前,我想验证我的学生是否处于活动状态,因此活动字段的值必须为1。我创建了一个存储过程来完成此操作。我似乎不明白insert与select如何连接,下面是我的尝试
下面是我的尝试:

INSERT INTO Grade  
VALUES(@gradeId, @grade, @examDate, @professorId, @subjectId, @studentId, @active) 

SELECT g.grade, g.examDate, g.professorId, g.subjectId, g.studentId
FROM grade g
JOIN student s ON s.studentId = g.studentId
WHERE s.active = 1 and @studentId = s.StudentId
lf5gs5x2

lf5gs5x21#

使用以下语句解决:

INSERT INTO Grade (GradeId, Grade, ExamDate, ProfessorId, SubjectId, StudentId, Active ) 
SELECT @gradeId, @grade, @examDate, @professorId, @subjectId, @studentId, @active
FROM student s
WHERE s.studentId = @studentId AND s.Active = 1

相关问题