T-SQL函数不返回所有值

时间:2013-06-15 08:18:07

标签: sql sql-server sql-server-2008 tsql sql-function

我有2个表,contactmembership

以下是我的表中的数据:

SERIALNUMBER    TITLE   FIRSTNAME   SURNAME
     1           Mr       John        Doe
     2           Mrs      Jane        Doe

成员:

MEMBERSHIPID    NAME    SERIALNUMBER
     1          TEST        1
     1          TEST        2

当我编写以下SELECT语句时:

SELECT * 
FROM CONTACT C
INNER JOIN MEMBERSHIP M
ON C.SERIALNUMBER=M.SERIALNUMBER
WHERE M.MEMBERSHIPID = '1'

我看到以下结果:

SERIALNUMBER    TITLE   FIRSTNAME   SURNAME MEMBERSHIPID    NAME    SERIALNUMBER
     1           Mr      John        Doe         1          TEST        1
     2           Mrs     Jane        Doe         1          TEST        2

然后我写了以下函数:

CREATE FUNCTION [dbo].[fnGetMemberNames] (@MEMBERSHIPID VARCHAR(100))
RETURNS VARCHAR(50)
BEGIN
  DECLARE @name_to_return AS VARCHAR(50);
  SET @name_to_return = NULL;
  SELECT  @name_to_return =
             (C.TITLE + ' ' + C.FIRSTNAME + ' ' + C.SURNAME) 
  FROM CONTACT C
  INNER JOIN MEMBERSHIP M
    ON C.SERIALNUMBER=M.SERIALNUMBER
    WHERE M.MEMBERSHIPID=@MEMBERSHIPID;
  RETURN @name_to_return ;

END;

我这样称呼函数:

SELECT [dbo].[fnGetMemberNames](1)

但我只得到一行结果。

Mrs      Jane        Doe

我应该看到带有Mr John Doe

的回车符或逗号分隔列表

1 个答案:

答案 0 :(得分:2)

CREATE FUNCTION [dbo].[fnGetMemberNames] (@MEMBERSHIPID VARCHAR(100))
RETURNS VARCHAR(max)
BEGIN
  DECLARE @name_to_return AS VARCHAR(max);
  SET @name_to_return = NULL;
  SELECT  @name_to_return = ISNULL(@name_to_return,'') +
             (C.TITLE + ' ' + C.FIRSTNAME + ' ' + C.SURNAME) + Char(13) + Char(10) 
  FROM CONTACT C
  LEFT JOIN MEMBERSHIP M
    ON C.SERIALNUMBER=M.SERIALNUMBER
    WHERE M.MEMBERSHIPID=@MEMBERSHIPID;
  RETURN @name_to_return ;

END;