为什么sql函数中的循环只执行一次?

时间:2014-04-01 16:23:49

标签: sql-server function tsql

给定CustomerInvoiceId,此函数应返回一串连接的项目编号。但是,我不明白为什么它只返回一个逗号,我想也许是因为它只执行一次。

ALTER FUNCTION [dbo].[ConcatProductNumbers] 
(
    @CustomerInvoiceId INT = 0
)
RETURNS VARCHAR
AS
BEGIN

-- Declare the return variable here
DECLARE @count INT = 0,
@i INT = 1,
@strProjectNumber VARCHAR(MAX) = '';
DECLARE @Ci_ProjectNumber TABLE
(
    Id INT NOT NULL IDENTITY(1, 1),
    ProjectNumber VARCHAR(50) 
)

-- Add the T-SQL statements to compute the return value here

INSERT INTO @Ci_ProjectNumber (ProjectNumber)
SELECT pa.ProjectNumber
FROM ProjectsActive pa
JOIN ProjectsActiveInvoicing pai
ON pa.OrderID = pai.OrderID
WHERE pai.CustomerInvoiceId = @CustomerInvoiceId;

SELECT @count = COUNT(*) FROM @Ci_ProjectNumber

WHILE @count > @i
    BEGIN
        SELECT @strProjectNumber = (@strProjectNumber + ', ' + ci.ProjectNumber)
        FROM @Ci_ProjectNumber ci
        WHERE ci.Id = @i;    

        SET @i = @i + 1;
    END

-- Return the result of the function    
RETURN @strProjectNumber 

END

但是,当我删除函数的定义时只保留语句内部并将RETURN @strProjectNumber替换为PRINT @strProjectNumber,它就可以了。有什么理由吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

如果目标是获得以逗号分隔的项目编号列表,则可以考虑使用COALESCE而不是循环。

SELECT @strProjectNumber = COALESCE(@strProjectNumber+',' ,'') + ProjectNumber
FROM ProjectsActive pa
JOIN ProjectsActiveInvoicing pai
ON pa.OrderID = pai.OrderID
WHERE pai.CustomerInvoiceId = @CustomerInvoiceId;



RETURN @strProjectNumber