如何创建复合键以及如何在其他表中将其作为外键引用
我有一个表,
create table tblcountry (
unqid uniqueidentifier
name varchar(100)
isremoved bit
)
我想在 unqid + isremoved 的基础上创建主键,其中 isremoved 必须为 true
我有另一个表:
create table tblstate (
unqid uniqueidentifier,
name varchar(100)
f_tblcountry uniqueidentifier,
isremoved bit
)
主要是我希望当我尝试将 isremoved 字段设为 true 或 1 时如果我在引用的表 tabstate 中使用了它,并且它使用其 isremoved 字段的记录不正确,那么它应该给我错误。如果该主键的 tabstate isremoved 为 true,那么它不应该给出任何错误。
I have a table following table
create table tblcountry (
unqid uniqueidentifier
name varchar(100)
isremoved bit
)
I want to create primary key on basis of unqid + isremoved and in which isremoved must be true
i have got another table:
create table tblstate (
unqid uniqueidentifier,
name varchar(100)
f_tblcountry uniqueidentifier,
isremoved bit
)
the main thing is that i want that when i try to make isremoved field as true or 1 of tabcountry than it should give me error if i have useid it in referenced table tabstate and the record to which it used its isremoved field is not true. and if the tabstate the isremoved is true for that primary key than its should not give any error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我执行了你的解决方案,它运行良好。当我在 tabcountry 中插入数据时,它让我插入,但是当我尝试插入到 tabstate 中时,
当我按照下面的查询插入到 tabstate 中时,
它会给我错误,我收到以下错误:
i executed your solution its running fine. when i insert data in tabcountry its let me insert but when i try to insert into tabstate its giveing me error
when i insert into tabstate as below query
i am getting following error:
对于值,主键仅确保它们是唯一的。当主键是复合键(由多个列组成)时,这意味着该键是所涉及的所有列的任意唯一组合。这意味着,如果主键同时是
unqid
和isremoved
- 以下内容将是表中的有效行:您的主键不应不包含
isremoved
列。为此,您需要一个外键引用,将
tblcountry
中的unqid
和isremoved
列关联到unqid
tblstate
表中的isremoved
列。约书亚的想法是正确的,但方向是错误的。
但这意味着,为了将记录插入
tblcountry
,您必须在tblstate
中已有unqid
值。具有外键约束的列可以为空 - 值为空不会触发外键约束 - 但您不能指定外键的一部分。要么满足外键,要么不满足。我不清楚你希望建模什么 - 如果我有更好的想法,我会提供替代方案。
With regards to values, a primary key only ensures that they are unique. When a primary key is a composite - comprised of multiple columns - it means that the key is any unique combination of all the columns involved. That means if the primary key is both
unqid
andisremoved
- the following would be valid rows in your table:Your primary key should not include the
isremoved
column.To do this, you need a foreign key reference associating the
unqid
andisremoved
columns in thetblcountry
to theunqid
andisremoved
columns in thetblstate
table.Joshua had the right idea, the wrong direction.
But this means that in order to insert a record into
tblcountry
, you must have theunqid
value already intblstate
. A column with a foreign key constraint can be nullable - the value being null won't trip the foreign key constraint - but you can not specify a portion of the foreign key. Either you satisfy the foreign key, or you don't.I'm not clear on what you were hoping to model - if I had a better idea, I would provide alternatives.