我正在研究Table-Valued函数,我需要一些帮助。这是我得到的,但看起来Table-value函数不喜欢在RETURN()语句中声明任何变量。
正如您所看到的那样,我正在捕获列名称(使用Declare / Set变量),但它似乎没有工作值表值。
请告知其他方法。如果可能,请提供一些示例代码。
谢谢,
Alter FUNCTION getCompanySaleYears()
RETURNS TABLE
AS
RETURN
(
-- //////// START: Get the Years and put them in the String for columns /////////
Declare @StartYear INT, @EndYear INT, @sql VARCHAR(MAX)
Declare @StrYears varchar(max);
Set @StartYear = 2011;
SET @EndYear = Year(Getdate());
SET @StrYears = ''
WHILE @StartYear <= @EndYear
BEGIN
SET @StrYears = @StrYears + ', [' + cast(@StartYear as varchar(10)) + ']'
SET @StartYear = @StartYear + 1
END
Select @StrYears = (SUBSTRING(@StrYears, 2, LEN(@StrYears)) )
-- //////// START: Get the Years and put them in the String for columns /////////
SET @sql = N'
SELECT CompanyID, ' + @StrYears + '
FROM (
SELECT CompanyID, SalesYear, SUM(TotalSO) AS TotalSO FROM (
SELECT c.CompanyID, o.OrderID, YEAR(o.CreatedDate) AS SalesYear
, ISNULL((Select SUM(ExtQty * UnitSell) FROM dbo.OrderDetail WHERE OrderID = o.OrderID ), 0) AS TotalSO
FROM dbo.Company c
LEFT JOIN Order o ON o.CompanyID = c.CompanyID
WHERE 1 = 1
--AND c.CompanyID = o2.CompanyID
AND YEAR(o.CreatedDate) BETWEEN ''2011'' And Year(Getdate())
) z
GROUP BY CompanyID, SalesYear
) x
PIVOT
(
Sum(TotalSO)
FOR SalesYear
IN (
' + @StrYears + '
)
) AS pvtSalesYear
'
PRINT @sql
EXEC (@sql)
)
答案 0 :(得分:0)
不幸的是,使用TVF无法做到这一点,因为SQL期望的是难以返回的架构,而不是像你所做的那样灵活。
您可以在TVF中拥有变量,只需要其他语法
ALTER FUNCTION ...() RETURNS @t TABLE(CompanyID int, ...) AS BEGIN
INSERT @t(CompanyID,...) SELECT companyid,... FROM dbo.Company c LEFT JOIN...
RETURN;
END;