Question

I'm updating an audit/log table that is populated by trigger when a table is updated. My intention is to use the sys.objects.object_id for table name and column name columns in the log table but it's not possible to use a FK reference for the system views. Is there any useful alternative to maintain referential integrity on the table?

Was it helpful?

Solution

You could use a trigger on the log table that rolls back when the object_id being inserted is not found in sys.objects - since triggers are the typical mechanism we use when a foreign key doesn't make sense or isn't possible (like maintaining integrity across database or instance boundaries).

But do you really want to lose all of the data because one column represents an object that no longer exists, or never existed? (Maybe that's ok; I don't what you're auditing/logging.) What is the likelihood of this happening since the trigger produces the object_id, and the system isn't known for messing up?

I'm not sure I understand the point anyway; while a foreign key to sys.objects would prevent someone from logging information about an object that doesn't exist, the presence of just one row in the logging table would make it impossible to ever drop that object. (Maybe that's ok too, but it doesn't sound wise.)

If the fear is that someday a user reviewing log history will hit a dead end because the object has since been dropped, a trigger that made sure the object existed when the row was inserted isn't going to have saved you from that scenario anyway. You'd need a DDL trigger maybe, on DROP_TABLE, so that either the log history associated with that table is purged, or the object_id is moved somewhere else so that you can still track down what that table used to be.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top