命名约束 vs 系统生成的约束

来源:互联网 发布:win8电脑优化 编辑:程序博客网 时间:2024/05/21 21:33
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

当你为一个表定义约束时,给约束命名是一个好习惯。另外,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 <script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击