0

Here is my code in Microsoft Visual Studio ASP.NET MVC4 using C#

int numRows = new SqlCommand("execute getRows", con);

Error message:

Cannot implicitly convert type 'System.Data.SqlClient.SqlCommand' to 'int'

Am I missing a step? Like do I have to do an ExecuteReader() type of thing?

I can't find a good resource on using SQL commands in ASP.NET MVC 4.

I know NOT to use string concatenation b/c of SQL injection, so I'm trying to use SQL Server stored procedure.

Here is the procedure:

CREATE PROCEDURE getRows
AS
BEGIN
    select COUNT(*) 
    from myTable 
    where Status = 1
END

Note: I have tried casting with (int) and with Int.Parse. I assume it has something to do with reading it? Or with making getRows procedure have an output?

2
  • 2
    ExecuteScalar() will help you in this case. Commented Sep 22, 2015 at 4:41
  • Yes that worked! Thank you Commented Sep 22, 2015 at 4:47

1 Answer 1

4

It's a little more complicated:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

int numRows = (int)cmd.ExecuteScalar();

sqlConnection1.Close();

More information.

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

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.