生成的 SQL 中存在奇怪的约束
注意:此问题与 Visual Paradigm 无关。懂SQL的人都可以回答。
我正在使用 Visual Paradigm 在我们的项目中对数据库进行建模(使用 ER 图)。当 Visual Paradigm 生成数据库的 SQL 等效项并将其导入 MSSQL 时,它工作得很好。
我查看了生成的 SQL 代码以确保一切正确,但我看到了一些奇怪的东西!:
对于 tblContracts
,我定义了一个名为 EndAfterStart
的约束来确保 tblContracts
的值code>endDate 始终大于 startDate
。为该约束生成的 SQL 代码如下:
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id=OBJECT_ID(N'[dbo].[EndAfterStart]'))
ALTER TABLE [dbo].[tblContracts] WITH CHECK ADD CONSTRAINT [EndAfterStart] CHECK (([startDate]<=[endDate]))
GO
ALTER TABLE [dbo].[tblContracts] CHECK CONSTRAINT [EndAfterStart]
GO
问题:
- 为什么
tblContracts
被更改两次以添加该约束?! - 前两行还不够吗?
- 第二行和第四行有什么不同?
Note: This question is not related to Visual Paradigm. Anyone that knows SQL could answer it.
I am using Visual Paradigm to model a database in our project (using ER diagrams). When Visual Paradigm generates the SQL equivalent for the database and I import it in MSSQL it works pretty.
I took a look in generated SQL code to make sure anything is right and I saw something strange!:
For tblContracts
I defined a constraint named EndAfterStart
to make sure the value of endDate
is always bigger than startDate
. The generated SQL code for this constraint is here:
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id=OBJECT_ID(N'[dbo].[EndAfterStart]'))
ALTER TABLE [dbo].[tblContracts] WITH CHECK ADD CONSTRAINT [EndAfterStart] CHECK (([startDate]<=[endDate]))
GO
ALTER TABLE [dbo].[tblContracts] CHECK CONSTRAINT [EndAfterStart]
GO
And the questions:
- Why
tblContracts
is altered twice to add this constraint?! - Isn't first two lines enough?
- What is different between second line and forth line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一行和第二行创建
EndAfterStart
约束(如果不存在)。第四行启用EndAfterStart
约束。First and second lines create
EndAfterStart
constraint if it doesn't exist. Fourth line enablesEndAfterStart
constraint.第二行将约束添加到表中;第四行启用约束。
The second line adds the constraint to the table; the fourth line enables the constraint.