1

我有 2 张桌子,contact并且membership

这是我表中的数据:

接触:

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

4

1 回答 1

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;
于 2013-06-15T08:24:07.197 回答