在SQL中的Table-returned-function中使用if语句的问题

时间:2009-12-10 13:45:15

标签: sql sql-server sql-function

我已将我的功能简化为以下内容:

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

我无法使它工作..似乎我有一些语法错误,但我无法弄清楚如何让它工作..任何想法?

4 个答案:

答案 0 :(得分:6)

如果要在函数中使用t-sql代码,则需要在'returns'部分中定义表,然后使用insert语句填充它:

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

答案 1 :(得分:2)

您必须在函数声明中声明具有临时名称和模式的表,然后在函数中插入它:

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

然后像:

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

这对于在表中插入多行的函数尤其有用。

或者,如果您只想返回单个SELECT的结果,则可以使用内联返回:

BEGIN
    RETURN (
        select t.TeamId from TblTeam t
            union
        select 1 as TeamId
    )
END

答案 2 :(得分:1)

正如Jeremy所说,或者它真的非常像你的简化例子:

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

(即您可能不必定义表var / schema)

答案 3 :(得分:0)

这段代码对我有用:

DROP FUNCTION IF EXISTS [dbo].[test] 
GO

CREATE FUNCTION [dbo].[TEST] 
(
	@ACTIVEONLY bit
)
RETURNS @TST TABLE (column1 char)
AS
BEGIN
	IF @ACTIVEONLY = 1
	BEGIN
		INSERT INTO @TST(column1) VALUES('A')
	END
	ELSE
	BEGIN
		INSERT INTO @TST(column1) VALUES('B')
	END
	RETURN
END
GO

SELECT * FROM [dbo].[TEST](1)
GO

SELECT * FROM [dbo].[TEST](0)
GO