Click here to Skip to main content
16,019,106 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello!!

I am working on an application in which i have to save the name of members of a group to another table other then the main table(as normalization is done ) .

Now i am using sql transactions to save the names into table.
The table structure of two tables are


For VisitorPass Table
unqid || PassNo || PassType || VisitorName || ToMeet || Department 

and some other fields


For GroupMember Table

unqid || PassNo || GroupMemberName


Now i have two stored procedures to enter data into these tables. In may Class file i have made functions which return String values from cmd.ExecuteNonQuery.ToString() (0 or 1)

Now if the passType is Group the i will have to save the names of members in GroupMembers Table.
I have done it upto here

C#
objMem.unqid = Convert.ToInt64(0);
           objMem.Passno = Convert.ToInt64(txtPassNo.Text);
           for (int i = 1; i<=Name.Count;i++ )
           {
               objMem.Visitorname = Name[1];
               con.Open();
               trns = con.BeginTransaction();
               y = objMem.fnSaveGroupMembers(trns);
           }


What i need to know is can i commit the transaction out of the foreach Loop and if so will it save all the name or just the last one? I will be saving data in both the tables if pass types is group so the transactions should commit only if both the tables get data.
Or can you suggest some other approach that i should try ???
Posted

1 solution

You have two options, depending on whether you want to treat saving each object as an atomic operation, or whether you want to treat the entire update as one.

In the first case you should wrap a single update into both tables in a transaction. This would probably actually be better as a stored procedure, but in code terms that would be, I think, a transaction inside the loop (committed after writing one row into both tables).

In the second, you would create a transaction before doing any saves and commit it after all of them.

In any case you shouldn't be calling Connection.Open inside the loop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900