I have the next problem:
The database in the system has denormalized tables with lets say “CompanyID” field held on almost every table in the database. This was done due to business rules purposes and should be that way. Sometimes the data is inconsistent as the Customer being with CompanyID == 1 has the order with CompanyID == 2.
My suggestion is to write specialized stored procedure which would be fired every once in a while and analyse some basic ‘relation chains’ on this property (meaning Cusomer with some Company ID should always have only Orders from the same Company ID where the latter has Articles with corresponding Company ID)
Quesqion:
Is there any generic way in SQL to fetch tables having field CompanyID and then checking them on consistency? Any other solutions to this problem?
I get the tables with the given column name using this SQL:
select column_name, c.is_nullable, c.table_schema, c.table_name, t.table_type, t.table_catalog, *
from information_schema.columns c join information_schema.tables t
on c.table_schema = t.table_schema and c.table_name = t.table_name
where column_name = 'CompanyID'
and table_type not in ('VIEW')
and t.table_name not like 'MsMerge%'
order by ordinal_position
After that I have in mind to traverse by foreign keys up the relation tree for record checking the equality of the CompanyID parameter.
I would not do that via a generic sql that runs every view minutes – this is the performance dead for big databases.
Instead you could use a Insert/Update Trigger on every effected table that you would code like that: