views:

77

answers:

4

I have simplified my function to the following:

create function [dbo].[UserSuperTeams](@ProjectId int) 
returns table 
as 
return 
   if @ProjectId=0
   begin 
      select TeamId from TblTeam t 
        union
      select 0 as TeamId
   end
   else
   begin
      select t.TeamId from TblTeam t
        union
      select 1 as TeamId
   end;
go

I cannot make it work.. It seems I have some syntax errors, but I cannot figure out how to make it work.. Any idea?

+2  A: 

You must declare the table with a temporary name and a schema in the function declaration, then insert into it in the function:

create function [dbo].[UserSuperTeams](@ProjectId int) 
returns @mytable table (TeamID int)  
as 
...

and then something like:

INSERT INTO @mytable 
select t.TeamId from TblTeam t
    union
select 1 as TeamId

This works especially well for functions that insert several rows into the table.

Alternatively, if you only wish to return the results of a single SELECT, you can use an inline return:

BEGIN
    RETURN (
        select t.TeamId from TblTeam t
            union
        select 1 as TeamId
    )
END
Jeremy Smyth
+2  A: 

If you are going to use t-sql code in the function, you need to define the table in the 'returns' section, then populate it with insert statements:

create function [dbo].[UserSuperTeams](@ProjectId int) 
  returns @results table (
    TeamId int
  ) as begin

  if @ProjectId=0 begin       
    insert @results (TeamId)
      select TeamId from TblTeam t
      union      
      select 0 as TeamId   
  end   
  else begin
    insert @results (TeamId)
      select t.TeamId from TblTeam t
      union      
      select 1 as TeamId   
end;

return
end
Ray
this will be parsed, but when executed, I get an error:"The last statement included within a function must be a return statement"
Stavros
There's also an "end" missing. Just add: "return; end" to the end of what Ray has given
AdaTheDev
I've updated Ray's answer, just to add the return statement in
AdaTheDev
lovely.. thanks
Stavros
oops - should check my own syntax :(
Ray
+1  A: 

As Jeremy said, or if it really is very like your simplified example you can do:

create function [dbo].[UserSuperTeams](@ProjectId int) 
returns table 
as 
return (select TeamId from TblTeam t 
        union
        select CASE WHEN @ProjectId = 0 THEN 0 ELSE 1 END as TeamId
       )
go

(i.e. you may not have to define the table var/schema)

AdaTheDev
my example was really simplified and this solution cannot be applied :(
Stavros
Ah ok. In which case, +1 to @Jeremy's solution. I'll leave my answer as it does highlight the potential use of an alternative dependent on the exact scenario
AdaTheDev
A: 

You are trying to use multi-line table valued function as a single-line (inline) one; for difference see here and here.

Damir Sudarevic