D
D
Dmitry Petrov2017-08-17 12:46:24
Transact SQL
Dmitry Petrov, 2017-08-17 12:46:24

How to count the number of external links (via foreign keys) per entry in a table?

There are three tables.
declare table_source (source_id int, nvarchar(10) value)
declare table_data1 (data_id int, source_id int)
declare table_data2 (data_id int, source_id int)
The table_data1 and table_data2 tables have foreign keys on the source_id columns to the table_source table.
How can you calculate how many records in table_data1 and table_data2 refer to a record in table_source WITHOUT KNOWING about the existence of table_data1 and table_data2?
That is, of course, you can write a query in the style of (select count(*) from table_data1 where source_id=XX) + (select count(*) from table_data2 where source_id=XX), but this should work so that at the stage of writing query, it is not known who is referencing and will refer to table_source in the future. Perhaps new tables or new keys will be added. Need a generic request.
Are there existing means for this or do we need to invent something?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
smirnoww, 2020-02-19
@smirnoww

Invent

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question