I have written a complex stored procedure that moves records between several tables based on complex logic. I have checked each little piece of the logic carefully but I want to have maximal confidence in the code. Is there a way to declare a logical relationship that must hold between the beginning and end of the SP? If these conditions are not met, I imagine that the SP will be rolled back.
Specifically, I want to declare that records in table A that are picked out by a set of logical conditions will be in table B (and not in table A) at the end of the SP and that records not picked out by those set of logical conditions will still be in table X at the end of the SP. I use a boolean function to pick out the records in A that match the conditions.
I know that I can test some of these things with nUnit but I am wondering if there is a way to declare and enforce this sort of logic within t-SQL itself.
If your records have a field containing a unique ID you can do a simple
INSERT+SELECTfrom TableA into TableB and then a simpleDELETEof the inserted original records.For instance first insert all the records matching your selection criteria into TableB:
And then delete from TableA all the records you just inserted into tableB using the field uniqueID as the selction criteria to determine which records to delete:
If you put both statements in a single transaction with a couple error checks you should be protected in case something goes wrong while the two statements are executing:
If you do not have a single column which can unique identify each of your records you can use
EXISTSinstead ofINfor selecting the records toDELETEfrom TableA: