Hello @Gani_tpt
Since you did not clarify, if you are trying to implement this logic on the front-end, the backend, or on the SQL itself, you have 3 possibilities to consider.
C# backend:
DateTime currentDate = DateTime.Now;
int differenceInYears = GetDifferenceInYears(admissionDate, currentDate);
if (differenceInYears > 5)
{
// Allow next admission
// Your logic here...
}
else
{
// Block user from entering admission date
// Your logic here...
}
In SQL proc you may implement this.:
CREATE PROCEDURE CalculateDifferenceInYears
@AdmissionDate DATE,
@CurrentDate DATE
AS
BEGIN
DECLARE @DifferenceInYears INT
-- Calculate the difference in years
SET @DifferenceInYears = YEAR(@CurrentDate) - YEAR(@AdmissionDate)
-- Adjust for leap years
IF MONTH(@AdmissionDate) = MONTH(@CurrentDate) AND DAY(@CurrentDate) < DAY(@AdmissionDate)
BEGIN
SET @DifferenceInYears = @DifferenceInYears - 1
END
-- Return the result
SELECT @DifferenceInYears AS YearsDifference
END
and then implement it with your front-end like this.
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("CalculateDifferenceInYears", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@AdmissionDate", yourAdmissionDate);
command.Parameters.AddWithValue("@CurrentDate", DateTime.Now);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
int differenceInYears = Convert.ToInt32(reader["YearsDifference"]);
// Your logic based on the differenceInYears here...
}
}
}
}
I hope this answers your question.