表值函数仅显示1个结果

时间:2017-03-29 12:53:08

标签: sql-server

我有这个表值函数,我希望它显示具有相同“PeopleID”的所有记录。我该怎么做?它目前只显示其中一个可能的结果。

ALTER FUNCTION dbo.ufnGetContactInformation(@FuncID int)
RETURNS @retContactInformation TABLE 
(
    -- Columns returned by the function
    FuncID int PRIMARY KEY NOT NULL, 
    Full_Name nvarchar(75) NULL, 
    Phone nvarchar(100) NULL, 
    Email nvarchar(50) NULL, 
    City nvarchar(20) NULL
)
AS 
BEGIN
    DECLARE
        @fullname nvarchar(75),
        @phonenumber nvarchar(100),
        @email nvarchar(50),
        @city nvarchar(20);

    -- > Get common contact information
    SELECT
            @fullname = p.Full_Name,
            @phonenumber = c.Phone, 
            @email = c.Email,
            @city = c.CityID
            FROM d_People p, d_Contacts c
            WHERE p.PeopleID=@FuncID;
    -- < Get common contact information
    IF @FuncID IS NOT NULL 
    BEGIN
        INSERT @retContactInformation
        SELECT @FuncID, @fullname, @phonenumber, @email, @city;
    END;
    RETURN;
END;
GO

1 个答案:

答案 0 :(得分:2)

您的两个表需要一个合适的join,否则您的查询没有意义。你现在拥有的只会给你一个人full_name,但每个联系人phoneemailcity

Bad habits to kick : using old-style JOINs - Aaron Bertrand

当您选择标量变量时,每个变量只能得到一个结果。将变量设置为仅保留一行后插入变量最多只能产生一行。

您可以将函数简化为内联表值函数,如下所示:

alter function dbo.ufngetcontactinformation(@funcid int)
returns table as return (
  select 
     funcid = p.peopleid
   , fullname = p.full_name
   , phonenumber = c.phone
   , email = c.email
   , city = c.cityid
  from d_people p, d_contacts c
  where p.peopleid = @funcid;
);
go

参考

如果必须具有多语句表值函数,尽管性能达到了打击:

alter function dbo.ufngetcontactinformation(@funcid int)
returns @retcontactinformation table 
(
    -- columns returned by the function
    funcid int primary key not null, 
    full_name nvarchar(75) null, 
    phone nvarchar(100) null, 
    email nvarchar(50) null, 
    city nvarchar(20) null
)
as 
begin
  insert @retcontactinformation
select 
    @funcid
  , p.full_name
  , c.phone
  , c.email
  , c.cityid
from d_people p, d_contacts c
where p.peopleid = @funcid;
return;
end;
go