當你為一個表定義約束時,給約束命名是一個好習慣。另外,sql server會為約束創建系統自動生成的名稱。當在沒有給約束命名的情況下,生成數據定義語言(ddl)(當ddl應用在幾個數據庫上時),那么系統生產約束名一般是不一樣的。
在為數據庫生成計劃后,再生成詳細的約束列表,與一個詳細計劃構造的合法約束列表進行對比,是一個很好的習慣。當數據庫相當大時,這樣做是非常有益的。
下面的腳本演示了命名約束、不命名約束及系統自動生成的約束名之間的區別,三者使用了同樣的表,只不過每次都是重新創建的:
create table parent
(pkey1 int not null
constraint pk_parent primary key (pkey1))
go
create table constraintname
(pkey int not null
constraint pk_cnstnm primary key,
parent_pkey1 int not null,
col1 int null
constraint ck_cnstnm_col1 check (col1 in ( 'a','b' ) )
constraint df_cnstnm_col1 default 1,
constraint fk_parent_cnstnm foreign key (parent_pkey1)
references parent (pkey1)
)
go
exec sp_helpconstraint constraintname
go
drop table constraintname
go
create table constraintname
(pkey int not null
primary key,
parent_pkey1 int not null
foreign key (parent_pkey1) references parent(pkey1),
col1 int null
check (col1 in ( 'a','b' ) )
default 1
)
go
exec sp_helpconstraint constraintname
go
drop table constraintname
go
create table constraintname
(pkey int not null
primary key,
parent_pkey1 int not null
foreign key (parent_pkey1) references parent(pkey1),
col1 int null
check (col1 in ( 'a','b' ) )
default 1
)
go
exec sp_helpconstraint constraintname
go
drop table constraintname
go
drop table parent
go
新聞熱點
疑難解答