C# SqlCommand.ExecuteScalar() seems to always result in an object with value 0. Using SQL Server 2012. This is happening with all stored procedures. Here is a very simple example:
CREATE PROCEDURE [dbo].[sp_IsUnitPackaged]
@Serial varchar(20)
AS
BEGIN
SET NOCOUNT ON
SELECT COUNT(serial_number)
FROM dbo.t_pql_contents
WHERE serial_number = @Serial
END
GO
When I execute this directly in SSMS with a known existing value supplied for @Serial, I get the expected results:
(No column name)
1
Return Value
0
When I execute in my C# app with the following code, the result
below is always 0:
string unit_serial = "something"; // The same known existing value
SqlCommand comm = new SqlCommand("sp_IsUnitPackaged");
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@Serial", SqlDbType.VarChar)
{
Value = unit_serial,
Direction = ParameterDirection.Input,
Size = 20
});
int result = 0;
using (SqlConnection conn = Utils.CONN)
{
conn.Open();
using (comm)
{
comm.Connection = conn;
Int32.TryParse(comm.ExecuteScalar().ToString(), out result);
}
}
I've seen some other questions asked very similar to this. The best answer I could find seemed to indicate that it is important that you not structure your stored procedure with a RETURN
statement when you are expecting to use it with ExecuteScalar
. As you can see, I'm not.
So, what am I missing here?
UPDATE: I've also tried adding a RETURN 0
statement to the end of my procedure so that I only have one result when executing in SSMS:
CREATE PROCEDURE [dbo].[sp_IsUnitPackaged]
@Serial varchar(20)
AS
BEGIN
SET NOCOUNT ON
SELECT COUNT(serial_number)
FROM dbo.t_pql_contents
WHERE serial_number = @Serial
RETURN 0
END
GO
Executing this in SSMS gives only the following result now:
(No column name)
1
This update to the procedure continues to give a scalar result of 0 in my app, though.