简体   繁体   中英

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);
}
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.

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);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM