繁体   English   中英

从C#调用存储过程时出错

[英]Getting an error when calling stored procedure from C#

从C#调用SQL Server中的存储过程时出现以下错误:

第1行:'spGet_Data'附近的语法不正确。

这是我的代码:

public string GetData (string destinationFile)
{
    string conectionString = "uid=One_User;pwd=One_Password;database=One_Database;server=One_Server";

    SqlConnection con = new SqlConnection(conectionString);
    SqlCommand sqlCmd = new SqlCommand();

    string returnValue = string.Empty;
    string procedureName = "spGet_Data";

    sqlCmd.CommandType = CommandType.StoredProcedure;
    sqlCmd = new SqlCommand(procedureName, con);

    sqlCmd.Parameters.AddWithValue("@FileName", destinationFile);
    con.Open();
    var returnParameter = sqlCmd.Parameters.Add("@ret", SqlDbType.VarChar);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    sqlCmd.ExecuteNonQuery();
    returnValue = returnParameter.Value.ToString();

    con.Close();
    return returnValue;
}

程序本身正确返回数据,我检查连接是否处于Open状态。

它还能做什么?

谢谢。

问题在于您创建命令两次。
在第一次初始化之后,您将CommandType正确设置为StoredProcedure ,但是再一次创建了命令,这次您忘记设置CommandType

只需删除第一个初始化,只留下第二个初始化并在初始化后移动CommandType设置

SqlConnection con = new SqlConnection(conectionString);
string returnValue = string.Empty;
string procedureName = "spGet_Data";
SqlCommand sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.CommandType = CommandType.StoredProcedure;

哎呦。 这是在做,虽然不正确 看到另一个答案。


请参见SqlCommand.CommandType 你需要告诉它被视为一个sproc调用。 例如

sqlCmd.CommandType = CommandType.StoredProcedure;

否则会导致无效的SQL语句(即在SSMS查询中逐字运行spGet_Data应产生类似的消息)。

您创建一个SqlCommand对象,然后设置它的CommandType属性,然后再次通过在命令对象上调用new来覆盖它。 写得正确,您的代码应如下所示:

public string GetData (string destinationFile)
{
   string conectionString = "uid=One_User;pwd=One_Password;database=One_Database;server=One_Server";
   SqlConnection con = new SqlConnection(connectionString);
   SqlCommand sqlCmd = new SqlCommand(procedureName, con); 
   sqlCmd.CommandType = CommandType.StoredProcedure;  
   string returnValue = string.Empty;
   string procedureName = "spGet_Data";

   sqlCmd.Parameters.AddWithValue("@FileName", destinationFile);
   con.Open();
   var returnParameter = sqlCmd.Parameters.Add("@ret", SqlDbType.VarChar);
   returnParameter.Direction = ParameterDirection.ReturnValue;

   sqlCmd.ExecuteNonQuery();
   returnValue = returnParameter.Value.ToString();

   con.Close();
   return returnValue;
}

另外,我强烈建议您使用Using语句包围SqlConnectionSqlCommand对象。 很像这样:

public string GetData (string destinationFile)
{
   using (SqlConnection con = new SqlConnection(connectionString))
   {
      using (SqlCommand sqlCmd = new SqlCommand(procedureName, con))
      {
      }
   } 
}    

以这种方式执行此操作的好处是更清晰的代码,并且由于您的命令和连接对象实现了IDisposable ,因此一旦它们超出范围,它们将由GC处理。

顺便说一句,你有'conectionString'拼写错误; 我在我的代码示例中修复了它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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