2

我尝试了各种方法来做到这一点,但似乎都没有。该例程不断返回 0,因为结果为空。

这是我的代码:

string strSql = "SELECT [ID] FROM [PurchaseOrder].[dbo].[FMSSupplier] where (ExternalRef = @ExternalRef) and (CompanyID = @CompanyID)";

try
{
     SqlCommand command = new SqlCommand(strSql);
     command.Connection = new SqlConnection(PO_ConnectionString);
     command.CommandType = CommandType.Text;
     command.Parameters.Add(new SqlParameter("@ExternalRef",SqlDbType.NVarChar ,50){Value = strExternalRef});
     command.Parameters.Add(new SqlParameter("@CompanyID", SqlDbType.Int) { Value = intCompanyID });
     if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
     var result = command.ExecuteScalar();
     if (result != null)
     {
         return (int)result;
     }
     else
     {
         return 0;
     }
}

我在 SQL Server 中对此进行了测试,记录存在:

SELECT [ID] 
FROM [PurchaseOrder].[dbo].[FMSSupplier] 
WHERE (ExternalRef = 'EDE01') and (CompanyID = 24)

记录 ID 不为零,并且 ConnectionString 在其他实例中有效。

这些是我的两个参数的值:CompanyID = 24 strExternalRef = EDE01

4

2 回答 2

1

首先也是最重要的,检查

 if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();

不保证连接会打开。为什么?

状态可以是:

    Broken
    Connecting
    //..etc

其次,我不知道您是否为值分配了一个 intCompanyID , strExternalRef值(也许您在片段中执行了您没有向我们展示的片段)...

如果这是第一个调试步骤,请尝试任何方式:

   try
    {
         SqlCommand command = new SqlCommand(strSql);
         command.Connection = new SqlConnection(PO_ConnectionString);
         command.CommandType = CommandType.Text;
         command.Parameters.Add(new SqlParameter("@ExternalRef",SqlDbType.NVarChar ,50){Value ="EDE01"});
         command.Parameters.Add(new SqlParameter("@CompanyID", SqlDbType.Int) { Value = 24});
         command.Connection.Open();
         var result = command.ExecuteScalar();
         if (result != null)
         {
             return (int)result;
         }
         else
         {
             return 0;
         }
}

 catch (Exception ex)
{
  MessageBox.Show(ex.Message);
}
于 2014-06-04T14:44:17.380 回答
0

确保您的参数使用与数据库列使用的相同的 SqlDbType。在我的情况下,当相关数据库列使用 NVarChar 时,我使用 SqlDbType.VarChar 设置命令参数。

于 2016-07-10T02:15:40.597 回答