給定一個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
的確定指標,它的工作原理。任何理由?
感謝您的幫助
將您的RETURNS行從「RETURNS VARCHAR」更改爲「RETURNS VARCHAR(8000)」 –
非常感謝。這就是答案。但你評論而不是寫一個答案。 – Richard77