SQL检查是否已运行“CHECK CONSTRAINT”?

时间:2013-10-02 13:00:10

标签: sql sql-server alter-table

第二个ALTER TABLE CHECK CONSTRAINT是否应该在IF (NOT) EXISTS中,以便脚本可以重复执行?

IF NOT EXISTS (
    SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME ='fk_RoleId'
)
BEGIN
    ALTER TABLE [dbo].[webpages_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [fk_RoleId] FOREIGN KEY([RoleId])
    REFERENCES [dbo].[webpages_Roles] ([RoleId])
END
GO

-- Put me in an IF ... () BEGIN ... END?
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [fk_RoleId]
GO

它不会导致任何错误,但是如果它应该在IF子句中,那么如何测试它是否已经运行(if包含哪些内容)?

1 个答案:

答案 0 :(得分:1)

如果您确实需要支票(没有必要),sys.foreign_keys有一列is_not_trusted

  

系统尚未验证FOREIGN KEY约束。