How to set “auto insert” foreign key value by using SQL Server?

孤者浪人 提交于 2020-05-16 20:36:05

问题


I have created two tables and also created a relationship between them.

Table students:

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

Table studentprofile:

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

and relationship:

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

But, when I wrote this line:

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

the value of StudentId (in table studentprofile) wasn't updated automatically. Why?

Can you tell me how to set the value of StudentId (in table studentprofile) can be inserted automatically whenever I insert into table students?


回答1:


There is no such thing as insert cascade.
You can implement such a thing by using a trigger for insert on your students table, inserting default values (or nulls) into the studentprofile table:

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

Note that your Address column is defined as not null and has no default value, this is why I've used the hard coded 'NO ADDRESS' for it.

However, I agree with the comments on your question: you would be better off inserting the data to the student profile using a different insert statement (perhaps inside a transaction with the insert to students).



来源:https://stackoverflow.com/questions/30847738/how-to-set-auto-insert-foreign-key-value-by-using-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!