從SQL Server 中的Information_Schema 取得外鍵引用
在SQL Server 中,外鍵在維護資料庫內的引用完整性方面發揮著至關重要的作用。要檢索有關外部鍵引用的信息,information_schema 可能是寶貴的資源。
檢索外鍵引用的查詢:
以下查詢擷取外鍵約束名稱、引用的表格和給定外鍵的列:
SELECT KCU1.CONSTRAINT_SCHEMA AS FK_CONSTRAINT_SCHEMA ,KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME ,KCU1.TABLE_SCHEMA AS FK_TABLE_SCHEMA ,KCU1.TABLE_NAME AS FK_TABLE_NAME ,KCU1.COLUMN_NAME AS FK_COLUMN_NAME ,KCU2.TABLE_SCHEMA AS REFERENCED_TABLE_SCHEMA ,KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME ,KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
注意: Information_schema 不包含索引。若要基於唯一索引尋找外鍵,請參閱 SQL Server 的專有資料表。
外鍵引用檢索範例:
考慮下列表格結構:
CREATE TABLE [dbo].[T_ALV_Ref_FilterDisplay] ( [FA_MDT_ID] [varchar](20) NOT NULL, [FA_NAME] [varchar](255) NOT NULL ) CREATE TABLE [dbo].[T_AP_Ref_Customer] ( [MDT_ID] [varchar](20) NOT NULL, [CUST_NAME] [varchar](255) NOT NULL ) ALTER TABLE [dbo].[T_ALV_Ref_FilterDisplay] WITH CHECK ADD CONSTRAINT [FK_T_ALV_Ref_FilterDisplay_T_AP_Ref_Customer] FOREIGN KEY([FA_MDT_ID]) REFERENCES [dbo].[T_AP_Ref_Customer] ([MDT_ID])
要擷取外鍵 [FA_MDT_ID]引用的表和列,請執行以下命令查詢:
SELECT FK_TABLE_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE FK_TABLE_NAME = 'T_ALV_Ref_FilterDisplay' AND FK_COLUMN_NAME = 'FA_MDT_ID'
結果會顯示:
FK_TABLE_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME ---------------|----------------------|------------------------- T_ALV_Ref_FilterDisplay | T_AP_Ref_Customer | MDT_ID
這表示[T_ALV_Ref_FilterDisplay]中的外鍵[FA_MDT_ID]引用了[Tomer_Ref_Comer_AP_ID]引用了[ ]中的[MDT_ID]列表。
以上是如何使用 SQL Server 的 INFORMATION_SCHEMA 檢索外鍵引用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!