1

我有以下功能:

CREATE FUNCTION fGetTransactionStatusLog
(
    @TransactionID  int
)
RETURNS varchar(8000) AS  
BEGIN 

declare StatusChanges cursor for
    select  NewStatusID, FirstName + ' ' + LastName AS UserName, Stamp, CAST(Notes AS varchar(8000)) AS Notes
      from TransactionStatusChanges tsc
        left join Users us ON tsc.UserID = us.UserID
      where TransactionID = @TransactionID ORDER BY StatusNum

declare @output varchar(8000)

declare @NewStatusID char(2)
declare @UserName varchar(255)
declare @Stamp datetime
declare @Notes varchar(8000)

set @output = ''

OPEN StatusChanges
  FETCH NEXT FROM StatusChanges INTO @NewStatusID, @UserName, @Stamp, @Notes
  WHILE @@FETCH_STATUS = 0
  BEGIN

    set @output = @output + RTRIM(CAST(@Stamp AS varchar(30))) + ': ' + @NewStatusID + ' by ' + @UserName +  CHAR(13) + CHAR(10)

    IF @Notes IS NOT NULL
    BEGIN
        set @output = @output + '---' + @Notes +  CHAR(13) + CHAR(10)
    END

    FETCH NEXT FROM StatusChanges INTO @NewStatusID, @UserName, @Stamp, @Notes
  END
CLOSE StatusChanges
DEALLOCATE StatusChanges

RETURN @output

END

现在,对于在任何记录中都没有任何注释的事务,该函数完全返回我想要的内容......对于在 TransactionStatusChanges 中至少有一条记录且具有非 NULL 注释字段的事务,我得到 NULL。

我不太明白,因为我在连接之前检查 @Notes 是否不为 NULL。

有任何想法吗?

注意:我使用 varchar(8000) 因为我不能在函数中使用文本。

4

1 回答 1

4

其中之一是 NULL

   set @output = @output + RTRIM(CAST(@Stamp AS varchar(30))) + ': ' + @NewStatusID + ' by ' + @UserName +  CHAR(13) + CHAR(10)

此外,您可以通过使用 ISNULL 或 COALESCE 处理包含 NULL 的列来简化代码

CREATE FUNCTION fGetTransactionStatusLog
(
    @TransactionID  int
)
RETURNS varchar(8000) AS  
BEGIN 

declare @output AS varchar(8000)

select @output = ISNULL(@output, '')
        + ISNULL(RTRIM(CAST(Stamp AS varchar(30))), '<NULL>')
        + ISNULL(NewStatusID, '<NULL>') + ' by '
        + ISNULL(FirstName + ' ' + LastName, '<NULL>') + CHAR(13) + CHAR(10)
        + ISNULL('---' + Notes +  CHAR(13) + CHAR(10), '')
from TransactionStatusChanges tsc
left join Users us ON tsc.UserID = us.UserID
where TransactionID = @TransactionID ORDER BY StatusNum

RETURN @output

END
于 2008-10-08T05:20:13.373 回答