1

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

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

4 回答 4

6

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

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
于 2009-12-10T13:53:31.990 回答
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
于 2009-12-10T13:52:05.553 回答
1

正如杰里米所说,或者如果它真的很像你的简化示例,你可以这样做:

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)

于 2009-12-10T13:54:34.937 回答
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

于 2018-01-11T15:29:15.917 回答