views:

68

answers:

4

If I have two tables A and B:

A(AId, a1, a2) B(BId, AId, b1, b2, b3)

On first thought , I wanted to write a sp (stored procedure) incorporates the two insert statements.

But, on a second I thought I felt it would be nicer if I had a separated sp to do an insert for the table B and another to do an insert for table A while calling the insert sp for B from within A.

Please which is the best approach?

+1  A: 

That depends: If you assume that you will be able to reuse the SP for B in another context (i.e. outside the SP for A), make a separate SP. Otherwise, having just one SP (in particular, if it's only a simple SP with two INSERT statements) might reduce the complexity of your DB layer.

Heinzi
Now another question bumped into my mind. I currently use TransactionScope from my business layer to manage transactions. Calling those two procedures as part of as part of a transaction would not be right in my view, because logically the insertion process for the two tables isn't a transaction. I don't know about performance though.
Colour Blend
Why is it not a transaction? Would it make sense to insert the row in table A, then do some processing (maybe from another client) and then insert the row in table B? If no, it should be atomic, which is exactly what a transaction ensures.
Heinzi
Thanks you Heinzi.
Colour Blend
A: 

I would say that from maintenance point of view, it is better to have two procedures, since it makes the design more clear and two short procedures are easier to understand and design than a large one. I don't know anyway if this approach would have any performance implications.

Konamiman
+1  A: 

Do two separate procedures. Even if you don't see a need to separate them now, usually the point will come in future, where you would like to do a separate insert on only one of both. Then you'll be happy to have split up the SPs. (separation of concerns)

MicSim
A: 

You could also create a view on two tables and use INSTEAD OF INSERT trigger on the view. This way you treat everything as one table .

CREATE VIEW dbo.vAB
AS
SELECT x.AId, a1, a2, BId, b1, b2 ,b3
FROM dbo.A AS x JOIN dbo.B AS y on x.AID = y.AID
go

CREATE TRIGGER dbo.myInsrt
ON dbo.vAB
INSTEAD OF INSERT
AS
BEGIN
 -- your code here to deal with both tables
END
Damir Sudarevic
I was reading your code snippet and came across "INSTEAD OF INSERT". I have never written a trigger before but the "INSTEAD OF..." is not quite clear to me. It taught i should be "ON INSERT" or something. Please clarify.
Colour Blend
INSTEAD OF fires before the actin happens, so you have full control.
Damir Sudarevic
Thank you very much.
Colour Blend