[英]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. 我想在C#中使用存储过程从SQL Server表中获取数据。 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#.
我想打印带有我将作为参数传递的id的城市,但我不知道在C#中使用类似参数的正确语法。
This is the C# code that I'm using: 这是我正在使用的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);
You don't put a where
condition when you call a stored procedure. 调用存储过程时,不要放置
where
条件。 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. where
条件必须是存储过程的主体应该比较里面id
你的城市表的列@ID
参数要传递到存储过程。 Secondly, ExecuteNonQuery
function which you have written at the end will not serve your purpose. 其次,你在最后编写的
ExecuteNonQuery
函数不能满足你的目的。 Use ExecuteScalar
function instead as given below: 使用
ExecuteScalar
函数,如下所示:
String cityName= command.ExecuteScalar();
I am assuming your stored procedure accepts parameter @ID
and returns matching city name in the form of table. 我假设您的存储过程接受参数
@ID
并以表格形式返回匹配的城市名称。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.