在@ table变量中返回多个值

时间:2011-08-11 17:51:07

标签: sql-server-2005

ALTER FUNCTION [dbo].[fn_DivisonCode] (@PeopleID int)
RETURNS @temptable TABLE (Code varchar(100), ID varchar(100))
AS
begin

DECLARE @stDeptCode VARCHAR(100)
DECLARE @peopleID VARCHAR(100)

SELECT 
      @stDeptCode = (COALESCE(@stDeptCode + ',', '') + CAST(PPL.DeptCode AS VARCHAR(5))),
      @peopleID = peopleID
FROM dbo.PPL
WHERE PeopleID = peopleID 

INSERT INTO @temptable(Code, ID) 
  VALUES(@stDeptCode, @peopleID)

return
end

SELECT [dbo].[fn_DivisonCode](23415)

当我调用该函数时,它应该返回2个值,但在这里它只返回@stDeptCod值而不是@peopleID。我在这里缺少什么吗?

由于

1 个答案:

答案 0 :(得分:2)

您正在为变量选择值。变量一次只能保存一个值,因此当您运行select语句时,它可以从表中选择一个,两个或100个值,但只有最后一个值在语句完成后存储在变量中。相反,将select和insert语句组合在一起,如下所示:

insert into @temptable(Code,ID)
  SELECT (COALESCE(@stDeptCode + ',', '')  +  CAST(PPL.DeptCode AS VARCHAR(5))), peopleID
    FROM dbo.PPL  
    WHERE @PeopleID = peopleID