Saturday, 31 January 2015

Why SQL Server allows NULLs for the BIT datatype

During the interview my friend was asked, why SQL Server allows NULLs for the BIT datatype.
I like to explain things with analogies and this is no different. Consider a table holding job applicants details for a Job Board Website. Something Like this:-


CREATE TABLE dbo.tblJobApplicants (
  CandidateID int,
  JobID int,
  DateApplied date,
  isApproved bit
)

-- Applicant is approved
INSERT INTO dbo.tblJobApplicants
  SELECT
    1,
    1,
    GETDATE(),
    1

-- Applicant is rejected
INSERT INTO dbo.tblJobApplicants
  SELECT
    2,
    1,
    GETDATE(),
    0

-- Applicant is in progress means just applied
INSERT INTO dbo.tblJobApplicants
  SELECT
    3,
    1,
    GETDATE(),
    NULL
The key field to note here is of course the BIT field which indicates the approval or disapproval of the applicant. Obviously, when a candidate applies to a job, the status of the applicant isn't known  means the applicant has not been accepted, nor rejected. I think, it is the only end of the application in which this field can make a meaningful value. Hopefully, this example helps explain just when you might require a NULL bit field.

That’s it!!…..Happy Programming...

Saturday, 17 January 2015

How to compare two dates in ASP.NET using JAVASCRIPT

In this article, i am going to show how to validate two dates in asp.net using JavaScript. It also make sure that difference between two dates should not be more than n number of days. In my case, i specified 7 but you can specify it according to your need.

function ValidateDate() {
                var startDate = document.getElementById("<%=txtDatefrom.ClientID%>");
                var endDate = document.getElementById("<%=txtDateTo.ClientID%>");
                //Get 1 day in milliseconds
                var oneDay = 1000 * 60 * 60 * 24;
                
                // to make sure end date is greater than or equal to start date
                if ((Date.parse(startDate.value) > Date.parse(endDate.value))) {
                    $(endDate).css('border', '1px solid red');
                    return false;
                }

                else {
                    // to make sure difference between two dates should not be more than 7 days
                    if (Math.round((Date.parse(endDate.value) - Date.parse(startDate.value)) / oneDay) > 7) {
                        $(endDate).css('border', '1px solid red');
                        return false;
                    }
                    $(endDate).css('border', '1px solid #d3cfc7');
                    return true;
                }
            }