2

I came across a stored procedure that is returning number of rows but am not sure how can I read number of rows here,

Stored procedure is:

CREATE PROCEDURE [dbo].[Document_Exists]
(
    @Url varchar(255)
)
AS
    SET NOCOUNT ON;

    SELECT COUNT(*) AS Rows 
    FROM Document_Instances 
    WHERE Url = @Url

Executed as

EXEC @return_value = [dbo].[Document_Exists]
     @SourceSiteUrl = N'https://cc23.dev.com/portal'

SELECT 'Return Value' = @return_value

trying to read it with this code

SqlCommand cmd1 = new SqlCommand("Document_Exists", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add(new SqlParameter("@Url", url));
SqlDataReader rdr1 = cmd.ExecuteReader();

while (rdr1.Read())
{

dunno what to do next

1
  • Any particular reason why you want to use a reader for this? It can be done with the sql command and an output parameter instead. Commented Jul 27, 2012 at 14:37

4 Answers 4

4

Where is the point to use SqlDataReader when you return a single value from your proc?

SqlCommand cmd1 = new SqlCommand("Document_Exists", conn); 
cmd1.CommandType = CommandType.StoredProcedure; 
cmd1.Parameters.Add(new SqlParameter("@Url", url)); 
int rows = Convert.ToInt32(cmd.ExecuteScalar()); 
Sign up to request clarification or add additional context in comments.

Comments

2

try

int rows = 0;
if(rdr1.Read()) {
    rows = (int) rdr1["Rows"];
}

Comments

1
int totalRows=0;
if(rdr1.Read())
{
    totalRows=  rdr1.GetInt32(rdr1.GetOrdinal("Rows"));
}

If you are retuning only a single value, I recommend you to use ExecuteScalar

Comments

1
int rowCount = dataReader.Cast<object>().Count();

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.