如何将复合唯一键添加到用户定义的 table 类型

How To add composite unique key to user defined table Type

如何将复合唯一键添加到用户定义的 table 类型,如下所示:

CREATE TYPE [dbo].[jobdata] AS TABLE(
    [emp_num] [smallint] NULL,
    [job_date] [date] NULL,
    [year] [smallint] NULL,
    [job_code] [smallint] NULL,
    [order_year] [smallint] NULL,
    [order_ser] [decimal](5, 0) NULL,

)
GO

我希望 emp_num,job_date 成为复合唯一键。

您无法更改用户定义的 table 类型,您需要删除并重新创建才能进行任何更改..

From MSDN..

User-defined types cannot be modified after they are created, because changes could invalidate data in the tables or indexes. To modify a type, you must either drop the type and then re-create it, or issue an ALTER ASSEMBLY statement by using the WITH UNCHECKED DATA clause.

下面是在 UserDefined Table Type

上创建唯一约束的方法
CREATE TYPE test AS TABLE 
( col1 VARCHAR(50)
, col2 INT ,
 unique (col1,col2)
);

注意:我们不能命名约束,所以像正常方式创建约束是无效的..

下面的例子

 CREATE TYPE test AS TABLE 
    ( col1 VARCHAR(50)
    , col2 INT ,
    constraint test  unique (col1,col2)
    );

ALTER TABLE jobdata ADD CONSTRAINT [Unique_emp_num_ob_date] UNIQUE (
    emp_num
    ,job_date
    )