sql server – How to get age

 

“datediff” function wont be helpful for calculating age in SQLSERVER.  Below query gives an idea on how to calculate age.

declare @bday datetime Set @bday = ‘2000-02-28 00:00:00.000’
declare @as_of datetime Set @as_of = ‘2002-03-01 00:00:00.000’

select
@bday,
@as_of,
Convert(Char(8),@as_of,112),
Convert(Char(8),@bday,112),
0 + Convert(Char(8),@as_of,112) – Convert(Char(8),@bday,112),
(0 + Convert(Char(8),@as_of,112) – Convert(Char(8),@bday,112)) / 10000

SQL Server dates

to get different type of dates based on a date.

select
getdate()
, cast(cast(getdate() as date) as datetime) today_00hrs
, dateadd(dd,-1, cast(getdate() as date)) as yesterday_date
, cast(dateadd(dd,-1, cast(getdate() as date)) as datetime) as yesterday_00hrs
, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear
, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) as StartOfMonth
, (DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)) StartOfLastMonth
, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-3, 0) as Startof3monthsback
, DATEPART(week, GETDATE())weekofdate
, DATEADD(yy,-1,getdate() ) LastYearSameDateTime
, (DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)) LastMonth_1stday00hrs
, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) CurrentMonth_1stday00hrs
,  DATENAME(year, ’12:10:30.123′)
,DATENAME(month, ’12:10:30.123′)
,DATENAME(day, ’12:10:30.123′)
,DATENAME(dayofyear, ’12:10:30.123′)
,DATENAME(weekday, ’12:10:30.123′);

float to nvarchar in sql server

when you need to select from one column of datatype float(which has phone number) and insert it in another column as nvarchar- cast wont work

cast : cast([Column_Name] as nvarchar(50)). The result will be in format 9.07235e+009 instead of a 10 digit number (phone number).

use SELECT STR([Column_Name],10,0) ** This is SQL Server solution, for other servers check their docs