Reputation: 3279
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
Upvotes: 2
Views: 5476
Reputation: 13476
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.
Upvotes: 0
Reputation: 14389
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);
}
Upvotes: 1