更改 Sql 表(将外键更改为表的第二个主键)

发布于 2024-08-27 05:01:10 字数 112 浏览 2 评论 0原文

我有一个带有主键(自动递增)和外键的sql表。现在我需要通过将外键修改为第二个主键来修改表,以便其值不允许重复。

如何在不影响数据的情况下更改表?需要sql代码。

问候, 维克斯

I've a sql table with a primary key(Auto Incremented) and a foreign key.Now I need to modify the table by modifying the foreign key to second primary key so that its values are not allowed to duplicate.

How do i alter my table without affecting the data? Need the sql code.

Regards,
Vix

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱倦旧时光 2024-09-03 05:01:10

如果我理解您的请求,您希望强制外键在给定表中唯一,因此您的架构如下所示:

Create Table Table1
(
    Id int not null primary key clustered
    , ForeignId not null
    , ...
    , Constraint FK_Table1_Table2
        Foreign Key ( ForeignId )
        References Table2( Id )
)

现在您希望强制ForeignId在此表中唯一,对吗?您将执行以下操作:

Alter Table Table1
    Add Constraint UC_Table1_ForeignId Unique Nonclustered ( ForeignId )

If I understand your request, you want to force the foreign key to be unique within the given table so your schema looks like:

Create Table Table1
(
    Id int not null primary key clustered
    , ForeignId not null
    , ...
    , Constraint FK_Table1_Table2
        Foreign Key ( ForeignId )
        References Table2( Id )
)

And you now want to force ForeignId to be unique in this table, correct? You would do the following:

Alter Table Table1
    Add Constraint UC_Table1_ForeignId Unique Nonclustered ( ForeignId )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文