如何重新定义字段中的约束?

时间:2017-05-29 05:19:28

标签: sql sql-server sql-server-2008

该表构建如下

create table schema1.detail(
ornum char(6) foreign key references schema1.menu(ornum),
num int,
pdname char(20),
price money check(price>0) default null,
amount int check(amount>0) not null,
primary key (ornum,num)
)

我希望将字段“金额”重新定义为amount>0 and amount<=1000 not null 但我不知道怎么做。

3 个答案:

答案 0 :(得分:3)

好吧,如果您已经在表中有数据,则需要保留它,以便您首先需要找出约束的名称(因为您的创建脚本不提供约束的名称,SQL Server会它会自动为您服务),然后删除约束并创建一个新约束 要做到这一点,你需要做这样的事情来找出表格中约束的名称:

SELECT   TABLE_NAME, 
         COLUMN_NAME, 
         CHECK_CLAUSE, 
         cc.CONSTRAINT_SCHEMA, 
         cc.CONSTRAINT_NAME 
FROM     INFORMATION_SCHEMA.CHECK_CONSTRAINTS cc 
         INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c 
           ON cc.CONSTRAINT_NAME = c.CONSTRAINT_NAME 
WHERE TABLE_NAME = 'detail'
AND cc.CONSTRAINT_SCHEMA = 'schema1'
ORDER BY CONSTRAINT_SCHEMA, 
         TABLE_NAME, 
         COLUMN_NAME 

然后你需要删除约束并重新创建它:

ALTER TABLE dbo.detail
DROP CONSTRAINT <constraint name> -- you got from the query above

ALTER TABLE detail
ADD CONSTRAINT CK_detail_amount CHECK(amount>0 AND amount<1000)

然而,因为这是一张全新的表格,我建议将所有表格放在一起并重新创建,这次使用适当的约束名称:

drop table schema1.detail;

create table schema1.detail (
ornum char(6),
num int,
pdname char(20),
price money null, -- there is no need for the default keyword here...
amount int check(amount>0) not null,
constraint PK_detail primary key (ornum,num),
constraint FK_detail_menu foreign key (ornum) references schema1.menu(ornum),
constraint CK_detail_price check(price>0),
constraint CK_detail_amount check(amount>0 and amount <1000)
);

为您的约束提供有意义的名称是最佳做法。

答案 1 :(得分:1)

<强>已更新

alter table schema1.detail drop constraint [yourConstraintName] ;
alter table schema1.detail add constraint [yourConstraintName] check (amount>0 and amount < 1000)

答案 2 :(得分:0)

检查约束,例如&#34; fieldname BETWEEN 0和1000&#34;

金额int check(金额&gt; 0和金额&lt; 1000)非空,