Question

I receive many change requests daily, asking for deleting or updating a record in a production environment.

I generally don't own databases so no triggers, history tables, etc.

For example

delete 
from orders 
where orderNo in ('x123', 'x124', 'x129')

what I usually have as precaution is the following:

1) find out how big is the table ->

sp_spaceused 'dbo.orders'

depending on the size of the table I backup the whole table or only the range affected by the delete/update

For example:

select * into tablebackups.dbo._MM_20140502_orders_1515 
from Orders
where orderNo in ('x123', 'x124', 'x129')

This allows me to recover the data if needs be.

2) I check for constraints, I specially look for tables that depend on this one, what type of constraints and if there are ON CASCADE DELETE/UPDATE.

sp_helpconstraint 'dbo.orders' 

Depending on the result of this I can go ahead open a transaction, fire the delete, and if it goes through COMMIT the transaction.

Questions:

  1. does anyone have a script to show ON CASCADE constraints?
  2. does anyone have a script to show dependent records?
Was it helpful?

Solution

If possible I create a database snapshot (enterprise edition only) or take a full backup with copy_only option. Always open a transaction before deletes or updates and commit only after I'm sure everything went well.

To find out about FKs, check sys.foreign_keys catalog view. For example, to see all FKs for a table with cascade action on update or delete, use this query:

select *
from sys.foreign_keys
where parent_object_id = object_id('your_table') and
(delete_referential_action = 1 or update_referential_action = 1)

Similarly, this query will return FKs for a table, listing columns comprising the key and the referenced table:

select fk.name as foreign_key_name, 
    object_name(pc.object_id) as parent_table, pc.name as parent_column, 
    object_name(rc.object_id) as referenced_table, rc.name as referenced_column
from sys.foreign_keys fk
inner join sys.foreign_key_columns fkc on 
fk.object_id = fkc.constraint_object_id
inner join sys.columns pc 
on fkc.parent_object_id = pc.object_id and fkc.parent_column_id = pc.column_id
inner join sys.columns rc 
on fkc.referenced_object_id = rc.object_id and fkc.referenced_column_id = rc.column_id
where fk.parent_object_id = object_id('your_table')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top