I've been hanging on to this snippet of code (from Brett J.) for quite a while now, mostly because I didn't think it was real. I mean, really, no professional programmer would ever retrieve an entire table and loop through each row, just to get a row count ... right? A few weeks later, I got a similar submission from Sanket. It feel to the bottom of the stack and I never got around to posting it. But just recently, Enigma sent in yet another example of this technique. It had to be posted.
So, here it is: Three different developers. Three different languages. One combined example.
static int GetTableRowCount(string tableName) { int count = 0; SqlCommand cmd = new SqlCommand(); cmd.Connection = getConn(); cmd.CommandText = "SELECT * FROM [" + tableName + "]"; SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { count += 1; } return count; }
Oh, and sorry for the terribly bad pun of a title. Hopefully the content makes up for it :-D.