Question

I have tried various ways of doing this, but none seems to work. The routine keeps returning 0 as result is null.

This is my code:

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;
     }
}

I have tested this in SQL Server, the record exists:

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

The record ID is NOT zero, and the ConnectionString works in other instances.

These are the values of my two parameters: CompanyID = 24 strExternalRef = EDE01

Was it helpful?

Solution

First and most important, the check

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

Doesn't guarrantue that the connection will open. Why?

State can be:

    Broken
    Connecting
    //..etc

Secondly I dont know if you assign a value to intCompanyID , strExternalRef values (maybe you do in snippet you dont show to us)...

Any way try if this work as a first debug step:

   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);
}

OTHER TIPS

Make sure that your parameter is using the same SqlDbType as the database column is using. In my case I was setting the command parameter with SqlDbType.VarChar when the related database column was using NVarChar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top