The Wheel, slightly eliptic

time to read 7 min | 1251 words

A similar piece of code ( in PL/SQL and cursors ) kept me busy for most of the day. I have translated it to C# because I really don't think that I could stand seeing another cursor today.

Figure out what it does (it is tricky). And see if you can suggest an improvement. Both SQL and C#/ VB/ C++ (whatever) are accepted.

public void You_Commited_Grave_Sin_In_A_Past_Life_And_Are_Now_Being_Punished()

{

    SqlConenction connection = new SqlConnection(connectionString);

    SqlCommand parentCommand = new SqlCommand(connection,

        "SELECT customerid FROM Customers WHERE Active = 1");

    IDataReader parent = parentCommand.ExecuteReader();

    while(parent.MoveNext())

    {

        int custId = parent.GetInt32(0);

        int myCounter = 0;

        int myAmount = 0;

 

        SqlCommand childCommand = new SqlCommand(connection,

            "SELECT amount FROM Transactions WHERE customerID = "+custId);

       

        IDataReader child = childCommand.ExecuteReader();

        while (child.MoveNext())

        {

            myCounter = myCounter + 1;

            myAmount = myAmount + child.GetInt32(0);

        }

        parentCommand.CommandText = "Update Customers SET TransactionsCount = " +
            myCounter +
", TransactionAmount = " + myAmount + " WHERE CustomerID = "
           
+ custId;

        parentCommand.ExecuteNonQuery();

    }

}

This piece of code is reponsible for me feeling like a tank has pass through me, several times. I'm so tired I can barely think.

When you fomulate plans of action, please remember that any plan involving any of the following will not be considered (Blunt instruments, Sharp instruments, guns, maces and atomic sumbarines).



Update: Fixed tyop in code