使用SQL Server中的非唯一列对另一个表创建约束
我有两个名为类别
和categoryAuthorizations
的SQL Server表。我想确保所有categoryAuthorizations.CategoryId
值均在categories.categoryid
中。两个表中的ID
列是主键
。两个表中的categoryId
列都是non-Inique
。因此,我不能使用外键约束来确保categoryId
上的参考完整性。
CREATE TABLE [dbo].[Categories](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[Category] [varchar](500) NOT NULL,
[Status] [bit] NOT NULL,
[Updates] [smallint] NOT NULL,
CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
CREATE TABLE [dbo].[CategoryAuthorizations](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[AuthCode] [varchar](10) NOT NULL,
[Status] [bit] NOT NULL,
[Updates] [smallint] NOT NULL,
CONSTRAINT [PK_CategoryAuthorizations] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
示例:
表:类别
ID | 类别 | 类别 | 状态 | 更新 |
---|---|---|---|---|
1 | 1 | 胎 | 1 | 0 |
2 | 1 | 轮胎 | 0 | 1 |
3 | 1 | 轮胎 | 1 | 2 |
4 | 2 | 制动器 | 1 | 0 |
表:类别authorizations
id | categoryId | authcode | 状态 | 更新 |
---|---|---|---|---|
1 | 1 | SAM | 1 | 0 |
2 | 2 | C chr | 1 | 0 |
3 3 | 3 | Sam | 1 | 0 |
categoryAuthorizations
中的最后一个记录,其中categoryAuthorizations.CategoryId = 3
永远不要允许BE插入是否应用了约束,因为category.categoryid
不包含3个值。
总结:如何有效地 在非独特列上应用参考完整性另一个桌子?是否存在可以帮助满足此标准的约束或其他数据库解决方案?
I have two SQL Server tables named Categories
and CategoryAuthorizations
. I want to ensure all CategoryAuthorizations.CategoryId
values are in Categories.CategoryId
. The Id
column in both tables are Primary Keys
. The CategoryId
column in both tables are non-unique
. Therefore, I cannot use foreign key constraint to ensure referential integrity on CategoryId
.
CREATE TABLE [dbo].[Categories](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[Category] [varchar](500) NOT NULL,
[Status] [bit] NOT NULL,
[Updates] [smallint] NOT NULL,
CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
CREATE TABLE [dbo].[CategoryAuthorizations](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NOT NULL,
[AuthCode] [varchar](10) NOT NULL,
[Status] [bit] NOT NULL,
[Updates] [smallint] NOT NULL,
CONSTRAINT [PK_CategoryAuthorizations] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
Example:
Table: Categories
Id | CategoryId | Category | Status | Updates |
---|---|---|---|---|
1 | 1 | Tire | 1 | 0 |
2 | 1 | Tire | 0 | 1 |
3 | 1 | Tires | 1 | 2 |
4 | 2 | Brakes | 1 | 0 |
Table: CategoryAuthorizations
Id | CategoryId | AuthCode | Status | Updates |
---|---|---|---|---|
1 | 1 | SAM | 1 | 0 |
2 | 2 | CHR | 1 | 0 |
3 | 3 | SAM | 1 | 0 |
The last record in CategoryAuthorizations
, where CategoryAuthorizations.CategoryId = 3
, should never be allowed to be inserted if a constraint is applied because Category.CategoryId
does not contain a value of 3.
To sum up: How can I effectively apply referential integrity on a non-unique column from another table? Is there a constraint or another database solution which can help meet this criteria?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论