我有表A
與列ID
上的主鍵和表B,C,D...
有一列或多列與A.ID
外鍵關係。SQL如何查詢引用特定外鍵值的表?
如何編寫一個查詢,向我顯示包含主鍵的特定值(例如17
)的所有表?
我想要通用SQL代碼可以取表名和主鍵值並顯示所有通過外鍵引用該特定值的表。
結果應該是表名列表。
我使用MS SQL 2012
我有表A
與列ID
上的主鍵和表B,C,D...
有一列或多列與A.ID
外鍵關係。SQL如何查詢引用特定外鍵值的表?
如何編寫一個查詢,向我顯示包含主鍵的特定值(例如17
)的所有表?
我想要通用SQL代碼可以取表名和主鍵值並顯示所有通過外鍵引用該特定值的表。
結果應該是表名列表。
我使用MS SQL 2012
不是一個理想的一個,但應該返回所需要的(表列表):
declare @tableName sysname, @value sql_variant
set @tableName = 'A'
set @value = 17
declare @sql nvarchar(max)
create table #Value (Value sql_variant)
insert into #Value values (@value)
create table #Tables (Name sysname, [Column] sysname)
create index IX_Tables_Name on #Tables (Name)
set @sql = 'declare @value sql_variant
select @value = Value from #Value
'
set @sql = @sql + replace((
select
'insert into #Tables (Name, [Column])
select ''' + quotename(S.name) + '.' + quotename(T.name) + ''', ''' + quotename(FC.name) + '''
where exists (select 1 from ' + quotename(S.name) + '.' + quotename(T.name) + ' where ' + quotename(FC.name) + ' = @value)
'
from
sys.columns C
join sys.foreign_key_columns FKC on FKC.referenced_column_id = C.column_id and FKC.referenced_object_id = C.object_id
join sys.columns FC on FC.object_id = FKC.parent_object_id and FC.column_id = FKC.parent_column_id
join sys.tables T on T.object_id = FKC.parent_object_id
join sys.schemas S on S.schema_id = T.schema_id
where
C.object_id = object_id(@tableName)
and C.name = 'ID'
order by S.name, T.name
for xml path('')), '
', CHAR(13))
--print @sql
exec(@sql)
select distinct Name
from #Tables
order by Name
drop table #Value
drop table #Tables
你想看看sys.foreignkeys
。我將開始從http://blog.sqlauthority.com/2009/02/26/sql-server-2008-find-relationship-of-foreign-key-and-primary-key-using-t-sql-find-tables-with-foreign-key-constraint-in-database/
給像
declare @value nvarchar(20) = '1'
SELECT
'select * from '
+ QUOTENAME(SCHEMA_NAME(f.SCHEMA_ID))
+ '.'
+ quotename(OBJECT_NAME(f.parent_object_id))
+ ' where '
+ COL_NAME(fc.parent_object_id,fc.parent_column_id)
+ ' = '
+ @value
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.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
你可以achive通過編寫一些SQL。我發表了一個例子,但它只是一個模型,展示了你可以做到的方式。
CREATE TABLE tempTable
(
TABLE_NAME varchar(255)
);
CREATE UNIQUE CLUSTERED INDEX Idx_tempTable ON tempTable(TABLE_NAME);
DECLARE @var2 nvarchar(max)
INSERT INTO tempTable
SELECT DISTINCT
TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%COLUMN_NAME%'
/*FOREACH result of the tempTable you could find if the COLUMN_NAME of the result(table) has the value you want*/
SET @var2 = 'SELECT TABLE_NAME FROM ' + tempTableResult + ' WHERE COLUMN_NAME=VALUE'
exec(@var2)
DROP TABLE tempTable
所以,你正在尋找一個ERD圖? – Elias
什麼RDBMS? FK關係是在「CREATE TABLE」規範中實際定義的,還是僅由值來定義? –
有現有的FK關係。我不在尋找一個圖表,我正在尋找可以防止由於現有的FK關係而在PK表中刪除行的表。 – CoderBrien