首页 > 数据库

Implementing Table Inheritance in SQL Server

时间:2009-04-23 12:54:31  作者:武树伟  我要投稿
Linux初探欢迎您的投稿,投放方法请点击这里查看,我们会定期赠送精美小礼品给优秀的投稿作者。海纳百川 取则行远!LinuxGoo欢迎您的到来。
Implementing Table Inheritance in SQL ServerBy Jeff Smith on 20 February 2008 http://www.sqlteam.com/When designing a database, we sometimes come acr......

Then, we simply create a foreign key relation back to the People table – but instead of just on the PersonID column, we create the constraint on both the PersonID and the PersonTypeID columns. With these constraints in place, we are guaranteed that Person will only have one type, and that they can only have data in the matching sub-table for that type.

There is a catch, however: we cannot create our sub-tables just yet; if we try it, we’ll get the following error:

create table Students 

(

  PersonID int primary key, 

  PersonTypeID as 1 persisted, -- student

  EnrollmentDate datetime, 

  foreign key (PersonID, PersonTypeID) references People(PersonID, PersonTypeID)

)



Msg 1776, Level 16, State 0, Line 1

There are no primary or candidate keys in the referenced table 'People' that 

match the referencing column list in the foreign key 'FK__Students__1F98B2C1'.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint. See previous errors.

This is because the unique constraint on the People table is just on the PersonID column, but we are trying to set up a foreign key constraint on the combination of PersonID/PersonTypeID. To handle this, we simply add an additional unique constraint to the People table, covering both PersonID and PersonTypeID:

drop table People

go



create 
如果您需转载 Implementing Table Inheritance in SQL Server,请注明来自LinuxGoo.com,其版权归原作者所有。请广大网友留言时遵纪守法,使用文明用语。如果您在应用中有什么问题,请在下面留言,我们会尽快解答。
来顶一下
近回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
相关文章
栏目热门