Dolev
Dolev

Reputation: 151

C# : how to use parameters for SQL Server stored procedure?

I want to use stored procedures in C# to get data from a SQL Server table. I want to print the city with the id that I'll pass as a parameter, but I don't know the correct syntax of using parameters like that for a stored procedure in C#.

This is the C# code that I'm using:

string connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;

using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();

    SqlCommand command = new SqlCommand("SP_GetCityByID where id = 2", conn);
    command.CommandType = CommandType.StoredProcedure;

    SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int);
    param.Direction = ParameterDirection.Input;

    command.ExecuteNonQuery();

    Console.WriteLine(param.Value);
}

Upvotes: 3

Views: 3176

Answers (2)

Kannan Kandasamy
Kannan Kandasamy

Reputation: 13959

provide parameter as below:

  string connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        SqlCommand command = new SqlCommand("SP_GetCityByID", conn);
        command.CommandType = CommandType.StoredProcedure;
        SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int).Value = 2;
        //param.Direction = ParameterDirection.Input;
        command.ExecuteNonQuery();
        Console.WriteLine(param.Value);

    }

Upvotes: 0

Akshey Bhat
Akshey Bhat

Reputation: 8545

SqlCommand command = new SqlCommand("SP_GetCityByID ", conn);

You don't put a where condition when you call a stored procedure. where condition needs to be inside the body of stored procedure which should compare the id column of your city table with @ID parameter you are passing to stored procedure. Secondly, ExecuteNonQuery function which you have written at the end will not serve your purpose. Use ExecuteScalar function instead as given below:

String cityName= command.ExecuteScalar();

I am assuming your stored procedure accepts parameter @ID and returns matching city name in the form of table.

Upvotes: 2

Related Questions