1

I have a query that I'm running in C# .cs file:

DataSet ds = db.ExecuteDataSet(System.Data.CommandType.Text, "SELECT count(*) as counter FROM [Table] where [Table].[Field] = 'test'");

I want to do is retrieve the value of "counter" in this query and "return" it as my functions return value.

How can I do that?

3
  • 1
    You have already gotten answers to your question. I just want to add that if the table contains a large amount of data, you may get significantly better performance by specifying an indexed field (such as the primary key) in the count function: "SELECT count(tableId) FROM Table ..." Commented Sep 24, 2009 at 18:37
  • That's a good point. Thanks. Commented Sep 24, 2009 at 18:54
  • "...you may get significantly better performance by specifying an indexed field...". Not sure why this would be so. Surely the important point for performance is whether there is an index on the column(s) in the where clause, (in this case "where [Table].[Field] = 'test'"). If not, there is going to be a table scan no matter whether you specify COUNT(*) or COUNT(PKColumn). Commented Sep 24, 2009 at 19:10

3 Answers 3

11

As the SQL query won't return a dataset but a scalar, you should use the .ExecuteScalar() method:

int count = (int)db.ExecuteScalar(System.Data.COmmandType.Text, "SELECT count(*) as counter FROM [Table] where [Table].[Field] = 'test'");

(It would be easier for us to provide an answer if you told us what type the db instance is of...)

Sign up to request clarification or add additional context in comments.

6 Comments

Database db = DatabaseFactory.CreateDatabase -- is this what you're referring to?
With your suggestion, I get an error stating cannot implicitly convert type object to int.
You have to cast. It. I updated the example to fix the error you received.
Changed it and got: Invalid expression term 'int'
Okay got it. I just removed the Ctype and casted it using (int) and it works now. Thank you.
|
1
DataSet ds = db.ExecuteDataSet(System.Data.CommandType.Text, "SELECT count(*) as counter FROM [Table] where [Table].[Field] = 'test'");
return Convert.ToInt32(ds.Tables[0].Rows[0]["counter"]);

2 Comments

I get an error: Cannot apply indexing with [] to an expression of type 'System.Data.DataTable'
When you initialized the dataset did you create a datatable for it?
-2

You also shouldn't be using inline SQL. This SELECT count should all be thrown into a stored procedure. The stored procedure should be called from your applications data access layer.

That is where reusability comes in, you start noticing that you just might need to call this function across various places in your web site / client app.

Just some tips!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.