用户定义 table 带有检查约束的类型

User defined table type with check constraint

我想创建一个 table 类型用于存储过程,但我想确保传递给 table 的参数之一是两个值之一。

如果我正确地解释了文档,唯一可用的列约束是主键,但如果我错了请纠正我。

这是我尝试过的方法:

create type dealerDisable as table
(id int not null,
dealerNo varchar(10) not null,
dealerName varchar(50),
disabling varchar(5),
constraint ratesOrAll 
check (disabling in ('Rates','All')),
dateAdded date)

这是我得到的错误,它并不是那么有启发性:

请参考Documentation。正确的语法应该如下所示。没有 CONSTRAINT 关键字

create type dealerDisable as table
(
    id int not null,
    dealerNo varchar(10) not null,
    dealerName varchar(50),
    disabling varchar(5),
        check (disabling in ('Rates','All')),
    dateAdded date
)

syntax for creating table types is a little more restrictive - it does not support named constraints, along with some other differences compared to CREATE TABLE.

CREATE TYPE dbo.dealerDisable AS TABLE -- ALWAYS use schema!
(
  id int not null,
  dealerNo varchar(10) not null,
  dealerName varchar(50),
  disabling varchar(5) check (disabling in ('Rates','All')),
  dateAdded date
);

当您尝试插入一个值时,您可以看到系统必须为 table 的每个实例创建一个唯一的约束名称:

DECLARE @d dbo.dealerDisable2;
INSERT @d VALUES(1,'blat','foo','None',getdate());

DECLARE @e dbo.dealerDisable2;
INSERT @e VALUES(1,'blat','foo','None',getdate());

错误:

Msg 547, Level 16, State 0
The INSERT statement conflicted with the CHECK constraint "CK__#BCAA5D0E__disab__BD9E8147".
...

Msg 547, Level 16, State 0
The INSERT statement conflicted with the CHECK constraint "CK__#AAF87C65__disab__ABECA09E".
...

如果你仔细想想这背后的机制,就很有道理了。对于 some 类型的约束,你只能在数据库中有一个同名的约束。这会产生相同类型的错误,例如:

CREATE TABLE #a(id int, CONSTRAINT PK1 PRIMARY KEY (id));

CREATE TABLE #b(id int, CONSTRAINT PK1 PRIMARY KEY (id));

现在,虽然您确实可以有任意多个同名的检查约束,但这可能只是语法的直接简化。