我有一个SELECT语句,它多次使用函数的结果。有没有一种方法可以为其分配一个变量,以便使语句更有效,而且我不必继续使用该功能?
过度简化的假设示例代码:
DECLARE @Total Decimal(18,2)
SELECT t.ClientName AS Customer, t.ClientID,
--This function returns total sales for the Client
@Total = dbo.functionSalesTotal(t.ClientID),
@Total AS Sales, (@Total * 0.13) AS Tax,
(@Total + (@Total *0.13)) AS TotalIncludingTax
FROM table t
答案 0 :(得分:1)
子查询或apply
是最好的方法:
SELECT t.ClientName AS Customer, t.ClientID,
v.total AS Sales, (v.Total * 0.13) AS Tax,
(v.Total + (v.Total *0.13)) AS TotalIncludingTax
FROM table t CROSS APPLY
(VALUES (dbo.functionSalesTotal(t.ClientID)) as v(total);