Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
--scenario

I am writing a scalar function.

SQL
alter function dbo.age-- 'anurag'
(
@name varchar(100)
)
returns varchar(100)
as		
begin
	declare 
	@year int,
	@month int,
	@days varchar(50),
	@dob datetime,
	@finalyear datetime,
	@dayleftyear varchar(50),
	@finalday varchar(40),
	@FINAL VARCHAR(100)

	set @FINAL='';

	select @dob=dob from dateofbirth where name=@name
	select @year=datediff(year,@dob,getdate())
	if (month(getdate()) < month(@dob))
	begin
	set @year=@year-1;
	end
	set @finalyear=dateadd(year,@year,@dob)
	select @month=datediff(month,@finalyear,getdate())
	if(day(@finalyear)>(day(getdate())))
	begin
	set @month=@month-1;
	end

	select @dayleftyear=dateadd(month,@month,@finalyear)
	select @finalday=datediff(day,@dayleftyear,getdate())

	set @FINAL=cast(@year as varchar(23)) + ' YEARS ' + cast(@month as varchar(50)) + ' MONTH ' + ' AND ' +  @finalday + ' DAYS OLD'

return @FINAL;
end

--SELECT dbo.age('anurag') as finalyear


--When i am executing the scalar function i am getting the result

1 row affected.

--------------------------------------------
But when i run the query this works

SQL
select name,dbo.age(name)as age from dateofbirth

name            dob                                 age
anurag	 1989-04-28 00:00:00.000	    24 YEARS 8 MONTH  AND 17 DAYS OLD
kishore	 1980-12-25 00:00:00.000	    33 YEARS 0 MONTH  AND 20 DAYS OLD
ruchi	 1989-11-15 00:00:00.000	    24 YEARS 1 MONTH  AND 30 DAYS OLD
abhi	 1991-01-14 00:00:00.000	    23 YEARS 0 MONTH  AND 0 DAYS OLD


------------------------------------------------
doubt : why i am getting in scalar function 

1 row affected insted of the result


when i pass the name as below 

SELECT dbo.age('anurag') as finalyear

--this should give me o/p :: 24 YEARS 8 MONTH  AND 17 DAYS OLD

but i am getting ::1 row affected

Kindly help where I am doing wrong
Posted
Updated 13-Jan-14 8:21am
v4
Comments
CHill60 13-Jan-14 14:31pm    
If you're running it in the SQL Query Analyser are you viewing the correct results view - i.e. not the messages view
anurag19289 13-Jan-14 22:55pm    
I was getting only the message view. I dropped the table ..and created the table and function again. Now its working

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900