使用SQL Server中的非唯一列对另一个表创建约束

发布于 2025-01-21 05:01:22 字数 2073 浏览 4 评论 0原文

我有两个名为类别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类别类别状态更新
1110
21轮胎01
31轮胎12
42制动器10

表:类别authorizations

idcategoryIdauthcode状态更新
11SAM10
22C chr10
3 33Sam10

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

IdCategoryIdCategoryStatusUpdates
11Tire10
21Tire01
31Tires12
42Brakes10

Table: CategoryAuthorizations

IdCategoryIdAuthCodeStatusUpdates
11SAM10
22CHR10
33SAM10

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文