![](/img/trans.png)
[英]How to create stored procedure in sql server and call that procedure from C# code behind with some parameters to that procedure
[英]C# : how to use parameters for SQL Server stored procedure?
我想在C#中使用存儲過程從SQL Server表中獲取數據。 我想打印帶有我將作為參數傳遞的id的城市,但我不知道在C#中使用類似參數的正確語法。
這是我正在使用的C#代碼:
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);
調用存儲過程時,不要放置where
條件。 where
條件必須是存儲過程的主體應該比較里面id
你的城市表的列@ID
參數要傳遞到存儲過程。 其次,你在最后編寫的ExecuteNonQuery
函數不能滿足你的目的。 使用ExecuteScalar
函數,如下所示:
String cityName= command.ExecuteScalar();
我假設您的存儲過程接受參數@ID
並以表格形式返回匹配的城市名稱。
提供如下參數:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.