[英]Unable to pass string as a parameter to a stored procedure in ASP.NET MVC
I am stuck with an issue of passing a string value as a parameter to a stored procedure in C# ASP.NET MVC. 我陷入了将字符串值作为参数传递给C#ASP.NET MVC中存储过程的问题。 Any help is greatly appreciated. 任何帮助是极大的赞赏。
I tried various options of setting the parameter, like 我尝试了各种设置参数的选项,例如
cmd.Parameters.AddWithValue("@P_ORG", pOrg);
cmd.Parameters.Add(pOrg);
Code snippet: 程式码片段:
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlParameter param = new SqlParameter()
{
ParameterName = "@P_ORG",
Value = pOrg
};
SqlCommand cmd = new SqlCommand("getCCM", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(param);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
//do something
}
}
I hope that below example will solve your problem. 我希望以下示例可以解决您的问题。
command.Parameters.AddWithValue("@parameterID", parameter1);
Official definition: 官方定义:
AddWithValue replaces the SqlParameterCollection.Add method that takes a String and an Object. AddWithValue替换采用字符串和Object的SqlParameterCollection.Add方法。 The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.Add overload that takes a String and a SqlDbType enumeration value where passing an integer with the string could be interpreted as being either the parameter value or the corresponding SqlDbType value. 由于SqlParameterCollection可能含糊不清,因此不建议使用采用字符串和对象的Add的重载。采用String和SqlDbType枚举值的Add重载在其中将整数与字符串传递可以解释为参数值或对应的SqlDbType值。 Use AddWithValue whenever you want to add a parameter by specifying its name and value. 每当您想通过指定参数名称和值来添加参数时,请使用AddWithValue。
Source: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 来源: https : //msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Similar issue links with solution: 类似问题与解决方案相关:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/e600eb8d-6c06-4c9e-ad37-5a7538c9accf/unable-to-execute-stored-procedure-with-parameters-in-mvc?forum=csharpgeneral https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/e600eb8d-6c06-4c9e-ad37-5a7538c9accf/unable-to-execute-stored-procedure-with-parameters-in-mvc?forum=通用
Difference between Parameters.Add and Parameters.AddWithValue Parameters.Add和Parameters.AddWithValue之间的区别
Kindly let me know your thoughts or feedbacks 请让我知道您的想法或反馈
Thanks 谢谢
Karthik MCP,MCSA 卡萨克MCP,MCSA
As said in comments by Pankaj Kapare, you have to add 正如Pankaj Kapare在评论中所说,您必须添加
SqlDbType = SqlDbType.VarChar
to your SqlParameter object. 到您的SqlParameter对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.