2014-04-01 205 views
0

給定一個CustomerInvoiceId,這個函數應該返回一串連接的項目號。但是,我不明白爲什麼它只返回一個逗號,我想也許是因爲它只執行一次。爲什麼tsql函數中的循環只執行一次?

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 

然而,當我刪除功能只保留了語句中,並與PRINT @strProjectNumber更換RETURN @strProjectNumber的確定指標,它的工作原理。任何理由?

感謝您的幫助

+1

將您的RETURNS行從「RETURNS VARCHAR」更改爲「RETURNS VARCHAR(8000)」 –

+0

非常感謝。這就是答案。但你評論而不是寫一個答案。 – Richard77

回答

1

如果目標是獲得一個逗號分隔的項目數的列表,你可以考慮使用COALESCE,而不是一個循環。

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



RETURN @strProjectNumber 
+0

如果ProjectNumber列可以包含NULL,那麼您應該在where子句中過濾:並且ProjectNumber IS NOT NULL –

+0

非常感謝。 – Richard77