The query will return a list of table names and append those names with the data (if used to find), or a "(no date)" if child data are held as daily instances.
Also, apologies up front for the use of a cursor. I tend to use them only for special cases such as this one (i.e. finding the few odd records that may exist across 100's of tables).
In my case, a table references just under 400 tables (all of which are generated automatically as part of a "learning" system), and depending on the type of entry saved, data may or may not written into these tables. A further twist is some of these data are also by-date, so the query must also check for the existence of a date column in each table with the foreign key (fortunately, in these instances the column will always be named "dt").
From the nearly 400 tables listed as referencing the "asset" table. Only a dozen tables actually held data for the particular entry I was investigating. All of the tables held the data as daily instances/detail.
The referenced table's name is "asset" and the Dynamic SQL includes a sub query (convert a human readable name to a primary key, used as a FK value).
The cursor query is from Gishu at How can I list all foreign keys referencing a given table in SQL Server?
DECLARE @TableName varchar(255)
DECLARE @FKeyColumn varchar(255)
DECLARE @rowcount int
DECLARE @sqlCMD NVARCHAR(500)
DECLARE @dt NVARCHAR(10) = '2008-08-25'
DECLARE @SymbolName NVARCHAR(9) = 'thingImLookingFor'
DECLARE @byDate varchar(255)
DECLARE TableCursor
CURSOR FOR select
t.name as TableWithForeignKey,
c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
fk.referenced_object_id = (select object_id from sys.tables where name = 'asset')
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName, @FKeyColumn
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlCMD = 'SELECT @rowcount=count(*) FROM ' + @TableName + ' WHERE ' + @FKeyColumn + '=(SELECT asset_id FROM asset WHERE primary_symbol=''' + @SymbolName + ''')'
SET @byDate = ' (no date)'
IF EXISTS(SELECT 1 FROM sys.columns
WHERE sys.columns.name = N'dt'
AND sys.columns.object_id = Object_ID(@TableName))
BEGIN
SET @sqlCMD = @sqlCMD + ' AND dt=''' + @dt + ''''
SET @byDate = ' (' + @dt + ')'
END
EXEC sp_executesql @sqlCMD, N'@rowcount int output', @rowcount output
IF(@rowcount=1) PRINT(@TableName + @byDate)
FETCH NEXT FROM TableCursor INTO @TableName, @FKeyColumn
END
CLOSE TableCursor;
DEALLOCATE TableCursor;