I have a scalar function that returns one value in SQL Server. I'm trying to get that value by calling ExecuteScalar, but it always returns NULL and C# throws a NullReferenceException.
I created a function that checks room availability; if the room is available, it should return the roomId, otherwise 0.
I'm calling that function in C# using ADO.NET, but in this case, it throws an exception.
ADO.NET code:
using (SqlConnection con = new SqlConnection(connectionString)) { var command = con.CreateCommand(); command.CommandType = CommandType.StoredProcedure; command.CommandText = "RoomAvailability"; con.Open(); int returnValue = (int)command.ExecuteScalar(); // The error happens on this line Console.WriteLine(returnValue.ToString()); } SQL Server scalar function:
ALTER FUNCTION RoomAvailability() RETURNS INT AS BEGIN DECLARE @availability INT IF EXISTS(SELECT TOP 1 Id FROM Romm_Details WHERE status = 'F') BEGIN SET @availability = (SELECT TOP 1 Id FROM Romm_Details WHERE status = 'F') END ELSE BEGIN SET @availability = 0 END RETURN @availability //RETURN NULL VALUE END Expected result :
- if room available return room Id
- else return 0