sql主外键

来源:百度知道 编辑:UC知道 时间:2024/05/25 09:06:29
大家好,问一个SQL问题。

--创建用户表(tb_user)
create table tb_user
(
userId int identity(1,1) primary key, --自增为1的标识符,主键
number nchar(10) not null,-- foreign key references tb_student(number), --学号(这里应以tb_student为参照设为外键)
password varchar(20) not null default '123456', --密码
)

--创建学生信息表(tb_student)
create table tb_student
(
studentId int identity(1,1), --自增为1的标识符,主键
number nchar(10) not null primary key,--学生学号,一个主键
studentname nchar(8) not null, --学生姓名
)

insert into tb_student(number,studentname) values('2006107218','姓名')

这个我应该怎么改写,才能在tb_student表中插入数据时,表tb_user表中字段number会自动添加与tb_student中number字段的值?

再麻烦大家帮我说一下主外键的关系,为什么定义的主外键,它却不能自动添加值?

主外键是从表引用主表中的值,那也就是说要保证我们的主表中有的信息从表中才能用。数据库是不会自动向从表中插入值的。除非在主表上建触发器,这样在触发器中项从表中插入值。

tb_student 标识不等於主键
引用主键就行了
通@@identity/IDENT_CURRENT( 'table_name' )
--得到