SQL Server 2012, Windows 2008 R2 Server
i am trying to create a function that takes a date range as parameters. It returns a resultset by selecting from a table for the given date range.
I getting this error: Msg 102, Level 15, State 31, Procedure emp_performance_fn, Line 23 Incorrect syntax near 'BEGIN'.
CREATE FUNCTION emp_performance_fn (@startDate varchar(10), @endDate varchar(10))
RETURNS TABLE as
begin
declare @vStartDate date;
declare @vEndDate date ;
set @vStartDate = cast(@startDate as date);
set @vEndDate = cast(@endDate as date);
RETURN
select emp_name, bugs_closed, avg_days_taken,
(case bugs_closed_bucket when 1 then 'Low' when 4 then 'High' else 'Medium' end)
bugs_closed_bucket2,
(case avg_days_taken_bucket when 1 then 'Low' when 4 then 'High' else 'Medium'
end) avg_days_taken_bucket2
from (
select emp_name, bugs_closed, avg_days_taken, ntile(4) over (order by
avg_days_taken) avg_days_taken_bucket,
ntile(4) over (order by bugs_closed) bugs_closed_bucket
from (
SELECT t1.emp_name emp_name, sum(t1.bugs_closed) bugs_closed,
avg(t1.avg_days_taken) avg_days_taken
FROM emp_performance t1
WHERE month_end_date between @vStartDate and @vEndDate
group by t1.emp_name
) v1) v2;
end;
Any ideas as to the cause of this? The SQL is valid (i ran it after commenting the WHERE clause). If i change the return type to INT and return 1, it compiles OK.
Fixed
modified the code to have this:
RETURNS @rtnTable TABLE (
emp_name varchar(100),
bugs_closed numeric,
avg_days_taken numeric,
bugs_closed_bucket_name varchar(100),
avg_days_taken_bucket_name varchar(100)
)
and
insert into @rtnTable select ....
later in the function body. That worked. Thanks for all the responses.