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
First and most important, the check
Doesn't guarrantue that the connection will open. Why?
State can be:
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: