user3127554
user3127554

Reputation: 577

Get result from query using stored procedure

My program contains a gridview of rows of which I want to check if they are already billed.

I do this by checking a column in which the ID of the item is stored.

I have the following stored procedure:

ALTER PROCEDURE [dbo].[getBilledItem]
    @itemID int 
AS
BEGIN

    SET NOCOUNT ON;

    SELECT [items].[dbo].[itemLine].itemID
    FROM [items].[dbo].[itemLine]
    WHERE description LIKE '%' + cast(@itemID AS VARCHAR(255)) + '%'

END

What I want to do in my program is to add the itemID when the stored procedure returns 1 row(s) affected but this doesn't work.

My code looks like:

 using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
                using (var command = new SqlCommand("getBilledItem", conn)
                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    command.Parameters.Add(new SqlParameter("@itemID", SqlDbType.Int)).Value = itemID;
                    conn.Open();

                    int amount = command.ExecuteNonQuery();

                    if (amount > 0)
                    {
                        AlreadyBilledIDs.Add(itemID.ToString());
                    }
                }

Even when my stored procedure does return a row, my program doesn't catch it.

What in my code am I doing wrong? I thought that CommandExecuteNonQuery would return the amount of affected rows? Why isn't this working in my case?

Upvotes: 0

Views: 95

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

What you need is ExecuteScalar method which is used when we have only one row with one column being returned or if we have multiple rows in that case too it will just selected first column of the first row.

So you can do :

int amount = Convert.ToInt32(command.ExecuteScalar());

if you need number of rows then you can use Count() in your stored procedure and the c# code will remain same, just modify your query to be:

SELECT Count([items].[dbo].[itemLine].itemID)
.............
.............

now you will have the total number of rows returned by query :

int count = Convert.ToInt32(command.ExecuteScalar());

Upvotes: 2

Related Questions