【问题标题】:Insert values in inheritance tables在继承表中插入值
【发布时间】:2020-09-07 09:57:21
【问题描述】:
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)
)

如何在student中插入值,注意一个student具有所有person属性?例如学生有namebirth_date等。

我试过了:

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

但这只是增加了一个人,我无法判断是不是学生。

【问题讨论】:

  • 您能否扩展您的问题,以便我们可以看到您如何知道您是在插入学生还是教师......即您是否有变量?
  • 另外我认为你有一个错误,adam 之后的一个额外的'

标签: sql sql-server tsql database-design sql-insert


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多