Problem with if-statement used at Table-returned-function in SQL

馋奶兔 提交于 2019-12-11 12:43:08

问题


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?


回答1:


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



回答2:


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



回答3:


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)




回答4:


this code is working for me :

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


来源:https://stackoverflow.com/questions/1881072/problem-with-if-statement-used-at-table-returned-function-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!