Sunday, June 30, 2013

Why is ORDER BY allowed in TVF but not in INLINE TVF?

There must be a real simple explanation which escapes me right now. Thanks.


Does it mean I can trick the database engine? Use TVF with ORDER BY instead of ITVF?



CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)
RETURNS @Sales TABLE (ProdID int, Name varchar(50), Total money)
AS
BEGIN INSERT @Sales
SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'Total'
FROM Production.Product AS P
JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID
JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID
JOIN Sales.Customer AS C ON SH.CustomerID = C.CustomerID
WHERE C.StoreID = @storeid
GROUP BY P.ProductID, P.Name
ORDER BY P.ProductID, P.Name;
RETURN ;
END
GO

CREATE FUNCTION Sales.ufn_SalesByStore1 (@storeid int)
RETURNS TABLE
AS
RETURN
(
SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'Total'
FROM Production.Product AS P
JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID
JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID
JOIN Sales.Customer AS C ON SH.CustomerID = C.CustomerID
WHERE C.StoreID = @storeid
GROUP BY P.ProductID, P.Name
ORDER BY P.ProductID, P.Name;
);
GO
/*
Msg 1033, Level 15, State 1, Procedure ufn_SalesByStore1, Line 13
The ORDER BY clause is invalid in views, inline functions, derived tables,
subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
*/





Kalman Toth Database & OLAP Architect sqlusa.com

New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012







No comments:

Post a Comment