How to check date is valid for Sql server or not?

April 16, 2013

I needed to check the date is valid for sql server or not before i pass it to Sql server so i did it using below code and it’s working fine…

static bool IsValidSqlDateTimeNative(string someval)
{
bool valid = false;
DateTime testDate = DateTime.MinValue;
System.Data.SqlTypes.SqlDateTime sdt;
if (DateTime.TryParse(someval, out testDate))
{
try
{
// take advantage of the native conversion
sdt = new System.Data.SqlTypes.SqlDateTime(testDate);
valid = true;
}
catch (System.Data.SqlTypes.SqlTypeException ex)
{

// no need to do anything, this is the expected out of range error
}
}

return valid;
}

Advertisements

Calculate age in year,month & days

April 8, 2013

Hi,

Here we are calculating age in years,months and days using a birth date of the person.

here is function to calculate a age,

public void TimeSpanToDate(DateTime d1, DateTime d2, out int years, out int months, out int days)
{
// compute & return the difference of two dates,
// returning years, months & days
// d1 should be the larger (newest) of the two dates
// we want d1 to be the larger (newest) date
// flip if we need to
if (d1 < d2)
{
DateTime d3 = d2;
d2 = d1;
d1 = d3;
}

// compute difference in total months
months = 12 * (d1.Year – d2.Year) + (d1.Month – d2.Month);

// based upon the ‘days’,
// adjust months & compute actual days difference
if (d1.Day < d2.Day)
{
months–;
days = DateTime.DaysInMonth(d2.Year, d2.Month) – d2.Day + d1.Day;
}
else
{
days = d1.Day – d2.Day;
}
// compute years & actual months
years = months / 12;
months -= years * 12;
}

the function use like this,

protected void btnCalculate_Click(object sender, EventArgs e)
{
int years = -1, months = -1, days = -1;
DateTime birthDate = Convert.ToDateTime(txtbirthdate.Text);
TimeSpanToDate(DateTime.Now, birthDate, out years, out months, out days);
lblAge.Text = “Years: ” + years.ToString() + ” ; Months: ” + months.ToString() + ” ; Days: ” + days.ToString();
}


Select the inserted/updated value to get affected rows in single query with OUTPUT keyword

April 3, 2013

Select the inserted/Updated Value to get affected rows in single query with OUTPUT keyword

for insert query,

Insert Into tblTest(Name) OutPut Inserted.TestID,Inserted.Name values(‘Juhi’)

Output you will get

Capture

The same thing for update ,

Update tblTest set Name=’Juhi Paunikar’ OutPut inserted.TestID,inserted.Name

The output you will get

bg.jpg Capture1 Enjoy “Sql Queries….!!!”