Wednesday, March 21, 2012

Saving 1-to-many records with sp and transaction?

I'm trying to save several records to an SQL Server 2000 database. The records are in a 1:Many relationship; i.e., there is one record that goes into a parent table, and several that go into a child table. I have to do this with stored procedure(s) that constitute one transaction.
Can anyone tell me how this might be done?
Thanks!

Hi,

you would start a transaction with a call to BEGIN TRAN. Then do the statements one by one and after every statement you'd need to check if @.@.ERROR is different to 0. if it is, error has happened and you need to call ROLLBACK TRAN to roll back the transaction (restore to the state before the transaction) and call return to stop the execution (because in default no-errors flow you run to COMMIT TRAN eventually and if you have already called ROLLBACK, you cannot call COMMIT anymore in the same transaction) and return a code indicating an error to the calling code. You flow through the statements like this and then at the end you call ROLLBACK TRAN, whuch indicates transaction has ended successfully and changes are committed

See following link forma good explanation:

Introduction to Transactions
http://www.sqlteam.com/item.asp?ItemID=15583

This example is from there:

Create Proc TranTest2
AS
BEGIN TRAN

INSERT INTO [authors]([au_id],
[au_lname],
[au_fname],
[phone],
[contract])
VALUES ('172-32-1176',
'Gates',
'Bill',
'800-BUY-MSFT',
1)

IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRAN
return 10
END

UPDATE authors
SET au_fname = 'Johnzzz'
WHERE au_id = '172-32-1176'

IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRAN
return 11
END

COMMIT TRAN
GO

In your own SQL you just first call the INSERT, then get the ID of the added record with SCOPE_IDENTITY (remember to check for errors for the transaction) and add child records using this ID a sparent id one by one.
Completely another point is that if you need to add varying amount of rows, when you probably might be tempted to do this using ADO.NET code and SqlTransaction object because dealing with SQL with these can be a bit nasty (nor not nasty but you might need to use CSVs whatsoever to get variable amount of data in OR split it into multiple stored procedures) . Here is a tutorial for using SqlTransaction in ADO.NET code
http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=451

|||Great! Thanks a lot for the reply. I was just talking to a co-worker before I saw your reply and we both also concluded that the ADO.NET transaction object is probably the only way to do this (with a variable number of records).
Thanks for the links, too!
sql

No comments:

Post a Comment