在继承表中插入值

问题描述 投票:0回答:1
CREATE TABLE projeto.Person (
    Person_Code         INT IDENTITY(1,1)   NOT NULL,
    birthDate           DATE                NOT NULL,
    Name                VARCHAR(50)         NOT NULL,
    PRIMARY KEY (Person_Code)
)

CREATE TABLE projeto.Student (
    Student_Code        INT REFERENCES projeto.Person (Person_Code),
    payment             INT NOT NULL,
    PRIMARY KEY (Student_Code),
)
CREATE TABLE projeto.teacher (
    payment             INT                 NOT NULL,
    teacher_Code        INT,
    PRIMARY KEY (teacher_Code),
    CHECK (payment > 350)
)

我如何在学生中插入价值观,注意学生具有所有人的属性?例如学生有namebirth_date

我尝试过:

INSERT INTO projeto.Person VALUES 
    ('1961-03-26', John Adam')

但是这只会增加一个人,我无法确定它是否是学生。

sql sql-server select database-design sql-insert
1个回答
1
投票

我想它是如何获得您要求的最近插入的Person_Code?在这种情况下,请使用scope_identity()

declare @BirthDate date, @Name varchar(50), @Payment int, @IsStudent bit, @IsTeacher bit, @NewPersonCode int;

-- SET THE RELEVANT VARIABLE VALUES

-- Insert person
insert into projeto.Person (BirthDate, [Name])
  select @BirthDate, @Name;

-- Get the Person_Code of the new person record
set @NewPersonCode = scope_identity();

-- Insert Student record if a student
insert into projeto.Student (Student_Code, Payment)
  select @NewPersonCode, @Payment
  where @IsStudent = 1;

-- Insert Teacher record if a teacher
insert into projeto.Teacher (Teacher_Code, Payment)
  select @NewPersonCode, @Payment
  where @IsTeacher = 1;
© www.soinside.com 2019 - 2024. All rights reserved.