T-SQL编程基于Variable的返回表

时间:2018-02-23 18:36:12

标签: sql tsql adventureworks

我一直试图让这项工作暂时搁置,但我无法弄清楚错误。

该函数需要根据输入日期返回一个表。如果输入年份在数据库中不可用,则该函数需要返回所有年份的数据,否则,它只需要返回指定年份的数据。

也许有人可以提供帮助。 我正在使用2014年AdventureWorks数据库。

由于

CREATE FUNCTION DBO.udf_fonction(@year INT)

RETURNS TABLE

AS

RETURN 

IF @year IN (SELECT DISTINCT(YEAR(OrderDate)) AS Years
         FROM Sales.SalesOrderHeader)

(
    SELECT YEAR(A.OrderDate) AS SalesYear,
    C.Name AS SalesTerritory, 
    D.Name AS SalesCountryName, 
    CASE(A.OnlineOrderFlag)
        WHEN 1 THEN 'Online'
        WHEN 0 THEN 'In-store'
    END AS SalesType,
    SUM(A.SubTotal) AS Montant

    FROM sales.SalesOrderHeader A
    INNER JOIN Sales.Customer B ON A.CustomerID = B.CustomerID
    INNER JOIN Sales.SalesTerritory C ON B.TerritoryID = C.TerritoryID
    INNER JOIN Person.CountryRegion D ON C.CountryRegionCode = D.CountryRegionCode
    WHERE YEAR(A.OrderDate) = @year
    GROUP BY YEAR(A.OrderDate), C.Name, D.Name, CASE(A.OnlineOrderFlag)
                                                    WHEN 1 THEN 'Online'
                                                    WHEN 0 THEN 'In-store'
                                                END
                                                )
ELSE (SELECT YEAR(A.OrderDate) AS SalesYear,
    C.Name AS SalesTerritory, 
    D.Name AS SalesCountryName, 
    CASE(A.OnlineOrderFlag)
        WHEN 1 THEN 'Online'
        WHEN 0 THEN 'In-store'
    END AS SalesType,
    SUM(A.SubTotal) AS Montant

    FROM sales.SalesOrderHeader A
    INNER JOIN Sales.Customer B ON A.CustomerID = B.CustomerID
    INNER JOIN Sales.SalesTerritory C ON B.TerritoryID = C.TerritoryID
    INNER JOIN Person.CountryRegion D ON C.CountryRegionCode = D.CountryRegionCode
    GROUP BY YEAR(A.OrderDate), C.Name, D.Name, CASE(A.OnlineOrderFlag)
                                                    WHEN 1 THEN 'Online'
                                                    WHEN 0 THEN 'In-store'
                                                END
                                                )
GO

0 个答案:

没有答案