【问题标题】:How to set "auto insert" foreign key value by using SQL Server?如何使用 SQL Server 设置“自动插入”外键值?
【发布时间】:2015-06-15 14:27:25
【问题描述】:

我创建了两个表,并在它们之间创建了关系。

students:

create table students
(
    [StudentId] NVARCHAR(50) NOT NULL PRIMARY KEY,
    [Name] NVARCHAR(50) NOT NULL
);

studentprofile

create table studentprofile
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
    [StudentId] NVARCHAR(50) NOT NULL,
    [Address] NVARCHAR(50) NOT NULL,
);

和关系:

alter table studentprofile
add constraint students_studentprofile_FK 
    foreign key (StudentId) 
    references students(StudentId) 
        on delete cascade on update cascade

但是,当我写下这一行时:

insert into students values('110111', 'Marik')

StudentId 的值(在表 studentprofile 中)没有自动更新。为什么?

你能告诉我如何设置StudentId(在表studentprofile中)的值可以在我插入表students时自动插入吗?

【问题讨论】:

  • 为什么inserting 会对update cascade 产生任何影响? insert != update
  • 你应该做 2 次插入。第一次插入students 没有studentprofile 表的Address 信息。
  • 另外,您希望将什么内容插入到学生档案中?两个表之间看起来是一对多的关系,因此您可以插入无限数量的行,您如何决定应该自动插入表中的内容?特别是当列不可为空时

标签: sql-server foreign-keys primary-key


【解决方案1】:

没有insert cascade这样的东西。
您可以通过在students 表上使用插入触发器来实现这样的事情,将默认值(或空值)插入studentprofile 表:

CREATE TRIGGER students_insert ON students AFTER INSERT
AS
    INSERT INTO studentprofile(StudentId, Address)
    SELECT StudentId, 'NO ADDRESS'
    FROM inserted

请注意,您的地址列被定义为非空且没有默认值,这就是我使用硬编码'NO ADDRESS' 的原因。

但是,我同意 cmets 对您的问题的看法:您最好使用不同的插入语句将数据插入学生个人资料(可能在插入学生的事务中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    相关资源
    最近更新 更多