简体   繁体   English

SQL添加带有检查的外键约束

[英]SQL add Foreign key constraint with check

I have the following query which is adding contraint. 我有以下查询,其中添加了约束。 but in order to add, i want to check if this key has already been used or not? 但是为了添加,我想检查这个密钥是否已经被使用?

ALTER TABLE HL7_MessageHierarchy  
 ADD CONSTRAINT fk_vMessageType FOREIGN KEY (vMessageType) 
       REFERENCES HL7_MessageType(vMessageType);

for example. 例如。 if i have to add a column, i can easily check if the table exists in sysobjects and its respective column exists in syscolumns. 如果我必须添加一列,我可以轻松地检查该表是否存在于sysobjects中,并且其相应的列是否存在于syscolumns中。

Is it possible to use the query multiple times without GO and without making any error indeed? 是否可以在没有GO的情况下多次使用查询,并且确实不会产生任何错误? if yes then how ??? 如果是,那么如何?

[EDIT] [编辑]

I don't know why my browser not allowing me to add comments so i am adding to Edit. 我不知道为什么我的浏览器不允许我添加评论,所以我要添加到“编辑”中。

I want to check if there exists any foreign key with same name. 我想检查是否存在具有相同名称的外键。 so if there is no data even then the query can make problem because the key may already be existing. 因此,即使没有数据,查询也会出现问题,因为该键可能已经存在。 I want to run the above script clean (ofcourse resident data does matter but that is perhaps a straight forward check?) [EDIT] 我想干净地运行上面的脚本(当然,驻留数据很重要,但这也许是直接检查吗?)[编辑]

my bad, i must have known that version is important... I believe its 2005... (will love to know if someone can tell for other versions too) 不好意思,我一定知道该版本很重要...我相信它是2005 ...(很想知道是否有人也可以提供其他版本)

I assume you mean 我想你是说

check the HL7_MessageHierarchy for values not inHL7_MessageType" 检查HL7_MessageHierarchy中的值是否不在HL7_MessageType中”

So, a query like this will tell you 因此,这样的查询将告诉您

SELECT *
FROM HL7_MessageHierarchy H
WHERE NOT EXISTS (SELECT *
      FROM HL7_MessageType T 
      WHERE H.vMessageType = T.vMessageType)

Also, I'd recommend using WITH CHECK too 另外,我建议您也使用WITH CHECK

ALTER TABLE HL7_MessageHierarchy WITH CHECK ADD
 CONSTRAINT fk_vMessageType FOREIGN KEY (vMessageType) 
       REFERENCES HL7_MessageType(vMessageType);

In SQL 2005, the recommended way of checking for the existence of objects is Catalog Views . 在SQL 2005中,推荐的检查对象是否存在的方法是Catalog Views The one you want is sys.foreign_keys : 您想要的是sys.foreign_keys

IF NOT EXISTS ( SELECT * FROM sys.foreign_keys 
                WHERE name = 'fk_vMessageType' )
BEGIN
    EXEC ('
    ALTER TABLE HL7_MessageHierarchy  
     ADD CONSTRAINT fk_vMessageType FOREIGN KEY (vMessageType) 
           REFERENCES HL7_MessageType(vMessageType)
    ')
END

I have wrapped the creation in EXEC to avoid confusing the parser. 我将创建内容包装在EXEC以避免混淆解析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM