Getting back a return value from a SQL Count query

  • Thread starter Thread starter Greg Smith
  • Start date Start date
G

Greg Smith

I am trying to write a SQL query that will return a record count to my C#
application. I wrote the following query:

ALTER PROCEDURE up_justification_duplicate
AS
SELECT COUNT(*)
FROM tblJustifications

RETURN COUNT(*)


The table has four records in it. Running the query in the IDE gets me the
following results:

Running dbo."up_justification_duplicate".
-----------
4
No more results.
(1 row(s) returned)
@RETURN_VALUE = 1
Finished running dbo."up_justification_duplicate".

I have tried to extract the count in my application but all I know how to do
is read the return value (always a 1) with a statement like "x =
da.SelectCommand.Parameters[0].Value.ToString();".
How do I get back the correct count, in this case 4?

Any help is greatly appreciated.
 
Greg,

The way you have it, the count is being returned in a result set. What
you want to do is execute the command getting the scalar. Call
ExecuteScalar on the SqlCommand you are using to access the database. If
you want to set the count to the return value, then you need to change your
stored procedure to return a value like this:

alter PROCEDURE up_justification_duplicate
AS
return select COUNT(*) from asset

Then you should be able to access the return value through the
parameters.

Hope this helps.
 
Back
Top