SQL Server:主键左键连接过程的外键

时间:2014-02-28 04:29:14

标签: sql-server tsql

似乎很多时候我需要5-15分钟才能加入已经拥有FK到PK关系的表格。

有没有办法创建一个过程来返回一个表,该表连接通过外键连接到它的所有表?

实施例

Exec getFKJoin(Some_Table)
  1. 在表格中查找外键

  2. 遍历每个外键并找到它的主键对应物(other_table)

  3. Some_Table left join other_table on Some_Table.FK = other_table.PK

  4. 结束迭代

  5. Some_Table

  6. 实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

这显示了您需要在每个步骤上查询的表,以便您可以在其上构建并在存储过程中自动化它:

--Look for foreign keys on TABLE

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS  -- query 1
WHERE constraint_type='FOREIGN KEY'
AND TABLE_NAME='Some_table'

SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE -- query 2
WHERE constraint_name='Constraint_name_from_query_1' 


--Iterate through each foreign key and find it's primary key counterpart (other_table)

SELECT UNIQUE_CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS -- query 3
WHERE constraint_name='Constraint_name_from_query_1'

SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE -- query 4
WHERE constraint_name='Unique_constraint_from_query_3' 


-- Some_Table left join other_table on Some_Table.FK = other_table.PK

select * from table_name_from_query_2 LEFT JOIN table_name_from_query_4  ON column_name_from_query_2 = column_name_from_query_4