Is it possible for a view to select columns from a table valued function ?
CREATE FUNCTION fnGetLatestOrderStatus(@OrderId int)
RETURNS TABLE
AS
RETURN
SELECT TOP (1) Status, TimestampUtc
FROM OrderStatusHistory
ORDER BY TimestampUtc DESC
GO
CREATE VIEW MyView AS
SELECT
OrderId,
CustomerId,
fnGetLatestOrderStatus(OrderId).Status AS OrderStatus,
fnGetLatestOrderStatus(OrderId).TimestampUtc AS OrderStatusTimestamp
FROM Orders
GO
SSMS doesn't like this with error
Cannot find either column "fnGetLatestOrderStatus" or the user-defined function or aggregate "fnGetLatestOrderStatus", or the name is ambiguous.
Is this what you want to do?
SELECT o.OrderId, o.CustomerId, flos.*
FROM Orders o CROSS APPLY
dbo.fnGetLatestOrderStatus(o.OrderId int) flos;
You need to call the table-valued function in the FROM
clause.
Its possible if you get the syntax right. Note:
CREATE VIEW MyView
AS
SELECT
OrderId
, CustomerId
, (select Status from dbo.fnGetLatestOrderStatus(OrderId)) AS OrderStatus
, (select TimestampUtc from dbo.fnGetLatestOrderStatus(OrderId)) AS OrderStatusTimestamp
FROM Orders
GO
NOTE: And Gordon's solution is probably a better fit to your problem, but I thought it worth pointing out the 2 mistakes for your reference
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.