一種檢查 SQL 2005 中是否存在外鍵的方法 (A way to check if foreign key exists in SQL 2005)


問題描述

一種檢查 SQL 2005 中是否存在外鍵的方法 (A way to check if foreign key exists in SQL 2005)

Is there an easy way to check if a foreign key exists for a column in a table? I am writing a script which will add the foreign key only if it does not exist.

‑‑‑‑‑

參考解法

方法 1:

You can use this script:

IF EXISTS (SELECT * 
           FROM sys.foreign_keys 
           WHERE object_id = OBJECT_ID(N'[dbo].[FK_NAME]') 
             AND parent_object_id = OBJECT_ID(N'[dbo].[MyTable]'))
BEGIN
    ‑‑ do stuff
END

This can be done if you expand out the table and right click on an existing FK and choose script key as "DROP TO" and then you will get a generated script from SQL.

方法 2:

Woo‑hoo!  I just spent the past two days doing this.

IF NOT EXISTS ( SELECT  name
                FROM    sys.foreign_keys
                WHERE   name = 'FK_Name' ) 
    ALTER TABLE table_name ADD CONSTRAINT FK_Name FOREIGN KEY (idcol) 
                           REFERENCES OtherTable(idcol)

(by Barbara JacksonCodeLikeBeakerristonj)

參考文件

  1. A way to check if foreign key exists in SQL 2005 (CC BY‑SA 3.0/4.0)

#sql-server-2005 #SQL #foreign-keys






相關問題

可更新查詢所需的最低權限 (Access Project) (Minimum permissions required for an updatable query (Access Project))

Sql中的WHERE,結合兩個快速條件會成倍增加成本 (WHERE in Sql, combining two fast conditions multiplies costs many times)

是否可以重構此語句以刪除子查詢? (Is it possible to refactor this statement to remove the subquery?)

Không gửi được tệp nhật ký bằng 'Tác vụ Gửi Thư' từ trình xử lý OnError (Sending the log file using a 'Send Mail Task' from the OnError handler fails)

擴展 SSRS 中的圖表功能 (Extending chart functionality in SSRS)

sql server 2005 數據庫郵件錯誤(操作已超時) (sql server 2005 database mail error (The operation has timed out))

從.NET應用程序到SQL Server的緩慢調用 (Sporadically Slow Calls From .NET Application To SQL Server)

我需要在 sql 中獲取 alldata whereclause? (i need to get alldata whereclause in sql?)

一種檢查 SQL 2005 中是否存在外鍵的方法 (A way to check if foreign key exists in SQL 2005)

如何在 SSIS 中調用存儲過程? (How do you call a Stored Procedure in SSIS?)

什麼會使桌子“變慢”? (What would make a table "slow?")

可以在這裡使用 Common Table 表達式來提高性能嗎? (Can Common Table expressions be used here for performance?)







留言討論