sql—如何定义应用于数据集表中多个列的唯一约束?

1mrurvl1  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(345)

我在.sql脚本文件中定义了下表。

CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT [PK_HwComponent] PRIMARY KEY ([HwComponentId]),
    CONSTRAINT (FK1_HwComponent] FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT (FK2_HwComponent] FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT (UI1_HwComponent] UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber]))

GO

我现在需要在数据集设计器中定义一个新表来匹配。
我相信我已经正确地定义了所有内容,除了需要将所有3列视为唯一约束的唯一约束。
如何在数据集设计器中定义此表的唯一约束?
sql ce服务4.0 sp1:vs prof 2017-版本15.8.7

c86crjj0

c86crjj01#

如果格式正确,代码应该可以工作。你有不该做的事:

CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT PK_HwComponent PRIMARY KEY ([HwComponentId]),
    CONSTRAINT FK1_HwComponent FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT K2_HwComponent FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT UI1_HwComponent UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber])
);

我建议你把所有的方括号都去掉。它们只会使代码更难编写、阅读和修改。

yftpprvb

yftpprvb2#

这对你有用吗?

CREATE UNIQUE INDEX ixYourConstraint ON HwComponent (col1, col2);

这篇类似的文章可能对您有所帮助:mssqlcompact,对两列或更多列的唯一约束

1qczuiv0

1qczuiv03#

感谢algef和gordon的回复。
很抱歉搞混了。我的错。:-)sql示例运行良好。我只是举个例子。实际上,我需要使用vs中的数据集设计器精确地表示这个表。
数据集设计器中的hwcomponent表
我的问题是在数据集设计器中没有成功地正确定义唯一组。我需要定义一个由hwcomponenttypeid、manufactureid和serialnumber列组成的唯一组。
有什么想法吗?
再次感谢您的帮助

相关问题