我创建了新的表值函数,然后意识到这种方法可能不是很好。主要问题(在我看来)是我在tvf
中使用了声明新表。我确信这对tvf
不是很好。
ALTER FUNCTION [dbo].[tvf_GetOnSaleDate]
(
@EntityType INT
)
RETURNS @Result TABLE(OnSaleDate DATETIME, EntityId INT)
BEGIN
DECLARE @Sales TABLE (SaleDate DATETIME, EntityId INT, SaleDateVenueDate DATE, CurrentVenueDate DATE)
INSERT @Sales (SaleDate, EntityId, SaleDateVenueDate, CurrentVenueDate)
SELECT SaleDate, EntityId, CAST(DATEADD(hour, vc.HoursOffset, SaleDate) AS DATE) AS SaleDateVenueDate, CAST(DATEADD(hour, vc.HoursOffset, GETUTCDATE()) AS DATE) AS CurrentVenueDate
FROM dbo.om_EntityOnSale AS es WITH (NOLOCK)
INNER JOIN dbo.event AS e WITH (NOLOCK) ON e.event_id = es.EntityId AND es.EntityType = @EntityType
INNER JOIN dbo.om_Venue AS vc WITH (NOLOCK) ON vc.Indux_Venue_Id = e.venue_id
INSERT @Result(OnSaleDate, EntityId)
SELECT [OnSaleDate] =
CASE
WHEN (SELECT COUNT([SaleDate]) FROM @Sales WHERE [SaleDateVenueDate] = [CurrentVenueDate] AND [EntityId] = sales.EntityId) > 0
THEN ISNULL((SELECT MIN([SaleDate]) FROM @Sales WHERE [SaleDate] > GETUTCDATE() AND [SaleDateVenueDate] = [CurrentVenueDate] AND [EntityId] = sales.EntityId),
(SELECT MAX([SaleDate]) FROM @Sales WHERE [SaleDateVenueDate] = [CurrentVenueDate] AND [EntityId] = sales.EntityId))
WHEN (SELECT COUNT([SaleDate]) FROM @Sales WHERE [SaleDateVenueDate] > [CurrentVenueDate] AND [EntityId] = sales.EntityId) > 0
THEN (SELECT MIN([SaleDate]) FROM @Sales WHERE [SaleDateVenueDate] > [CurrentVenueDate] AND [EntityId] = sales.EntityId)
WHEN (SELECT COUNT([SaleDate]) FROM @Sales WHERE [SaleDateVenueDate] < [CurrentVenueDate] AND [EntityId] = sales.EntityId) > 0
THEN (SELECT MAX([SaleDate]) FROM @Sales WHERE [SaleDateVenueDate] < [CurrentVenueDate] AND [EntityId] = sales.EntityId)
END, sales.[EntityId]
FROM @Sales sales
GROUP BY EntityId
RETURN
END
如何优化此功能?
答案 0 :(得分:0)
对于此操作,内联表值函数应该没问题,但我认为您不需要销售表变量,我认为您现在可能不会从我正在阅读的代码中得到您想要的结果我试图推断你的架构。但是,您没有给出表格数据和预期结果的示例。我对你如何选择你的OnSaleDate有点困惑,你选择的是相同列的最大值或最小值,这取决于entityid所代表的值可能是相同的值。 SaleDate在哪个表上?