我想找到一组包含以下内容的表:
我正在使用:
EXEC sp_fkeys 'MyTable'
这会将具有外键约束的所有表返回给'MyTable',但我想进行额外的过滤。
由于我在我的数据库中有一个特别大的结果表列表,我想用包含任意列名的表来过滤FKTABLE_NAME
,例如CreatedOn
,这是不一定是链接列。
答案 0 :(得分:1)
这样的东西会查找包含FK到" yourtablename"的表格。其中引用表有一列" yourcolumnname"
SELECT
OBJECT_NAME(f.parent_object_id) TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
,*
FROM
sys.foreign_keys AS f
INNER JOIN
sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN
sys.tables t
ON t.OBJECT_ID = fc.referenced_object_id
WHERE
OBJECT_NAME (f.referenced_object_id) = 'yourtablename'
AND EXISTS (SELECT 1 FROM sys.columns c WHERE c.name='yourcolumnname' AND c.object_id=f.parent_object_id)
答案 1 :(得分:1)
您将在下面获得列表。然后,您可以选择不同的表名称并应用您需要的任何其他过滤器。
--build your temp table with output of SP_FKeys
CREATE TABLE #Temp (
PKTABLE_QUALIFIER VARCHAR(100),
PKTABLE_OWNER VARCHAR(100),
PKTABLE_NAME VARCHAR(100),
PKCOLUMN_NAME VARCHAR(100),
FKTABLE_QUALIFIER VARCHAR(100),
FKTABLE_OWNER VARCHAR(100),
FKTABLE_NAME VARCHAR(100),
FKCOLUMN_NAME VARCHAR(100),
KEY_SEQ INT,
UPDATE_RULE int,
DELETE_RULE int,
FK_NAME VARCHAR(100),
PK_NAME VARCHAR(100),
DEFERRABILITY int
)
--Populate it
INSERT INTO #Temp
EXEC sp_fkeys @pktable_name = N'Department'
,@pktable_owner = N'HumanResources';
--Now, join to systables and syscolums
SELECT * FROM #Temp TEMP JOIN sys.tables ST ON TEMP.FKTABLE_NAME = ST.name
JOIN sys.columns SC ON ST.object_id = SC.object_id
WHERE SC.name = 'CreatedOn' --enter your column name here