Monday, April 26, 2010

Getting the Numerics from a String Value

Declare @sVal varchar(100)
Select @sVal= 'Here is where15234Numbers'
Select @sVal= SubString(@sVal,PATINDEX('%[0-9]%',@sVal),Len(@sVal))
Select @sVal= SubString(@sVal,0,PATINDEX('%[^0-9]%',@sVal))
Select @sVal

OutPut
-------
15234

if the string is 'Here is where15.234Numbers'
Then use
Select @sVal= SubString(@sVal,0,PATINDEX('%[^0-9,.]%',@sVal))

OutPut
------
15.234

Tuesday, April 20, 2010

Getting the Date Difference in Years, Months and Days

CREATE PROCEDURE dbo.CalculateAge
@dayOfBirth datetime
AS

DECLARE @today datetime, @thisYearBirthDay datetime
DECLARE @years int, @months int, @days int

SELECT @today = GETDATE()

SELECT @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)

SELECT @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END)

SELECT @months = MONTH(@today - @thisYearBirthDay) - 1

SELECT @days = DAY(@today - @thisYearBirthDay) - 1

select @thisYearBirthDay
SELECT @years [Years], @months [Months], @days [Days]