Sometimes you want to check if a record exist before to go further with the program flow

Therefor it's nice to receive a bool return value from a stored procedure indicating if a record exist or not. But that's not possible. What is possible is to return a 1 or 0 indicating the count for the record. The stored procedure would then look like this:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Teus van Arkel
-- Create date: 18 januari 1015
-- Description:	Check if record exists
-- =============================================
ALTER PROCEDURE [dbo].[spCheckIfCustomerExist] 
	-- Add the parameters for the stored procedure here
	@customerId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	select  COUNT(*) from Customers where id = @customerId
	return
END 

Now you can catch this value in your logic and parse it to a bool, that is going to look like this:

public bool CustomerExist(int customerId )
        {
            // var
            bool exists = false;

            // execute
            try
            {


            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                using ( SqlCommand sqlCommand = new SqlCommand(deStoredProcedure, sqlConnection  ))
                {
                    sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

                    sqlCommand.Parameters.Add(new SqlParameter("@customerId", customerId));

                    sqlConnection.Open();

                    int customerCount =  (int) sqlCommand.ExecuteScalar();
                    exists = Convert.ToBoolean(customerCount);

                    sqlConnection.Close();
                }
            }
            }
            catch (SqlException sExc)
            {
                foreach (SqlError sqlError in sExc.Errors)
                {
                    switch (sqlError.Number)
                    {
                         // sql error number handling
                    }
                }
            }
            return exists;
        
        } 

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!