Search code examples
c#sqldatareadersqldatatypestype-equivalence

Variable holding a sql money data type doesn't update (C#)


I have a column type money in my sql server database, which is moneyAcumulated. Then with a command object I execute a store procedure that -among others things- brings the value for the column moneyAcumulated. Then in the while loop I store in variables all the values for each column the store procedure returns.

SqlCommand command = new SqlCommand("getTickets", Connection.getConnection());
            command.CommandType = CommandType.StoredProcedure;

            SqlDataReader reader = command.ExecuteReader();

            string bet = "";
            decimal moneyAcumulated = 0.0M;
            string id= "";
            string name = "";
            int cod = -1;
            decimal prize = 0.0M;
            while (reader.Read())
            {
                bet = reader.GetString(0);
                moneyAcumulated = reader.GetDecimal(1); // This variable doesn't chage its value
                name = reader.GetString(2);
                id = reader.GetString(3);
                cod = reader.GetInt32(4);
            }

First time while loop iterates each variable takes the correct value (including moneyAcumulated that brings the reader, but second time moneyAcumulated doesn't change its value and the others do, why?


Solution

  • The problem is that the SqlDataReader load all the data returned by the command.ExecuteReader in memory then if the data changes in the database, they would not change in the memory, I thought they would change every time the program execute the reader.Read() method, so that's why is was not working. And as the moneyAcumulated field in database is the same initially for all the tuples that confused me more, because the others were changing while moneyAcumulated wasn't.