我的代码中有一个标量函数调用另一个调用另外两个表的标量函数,如下所述。我知道这必须像猪一样表现。它在整个数据库中使用...我的问题是它在开发技能之外有点将其重写为表值函数。
我试图赢得一些开发人员重写函数,但我们只有JAVA人员而且没有专门的SQL开发人员,所以他们没有看到任何问题。任何人都可以建议如何重写这个?非常感谢...
CREATE FUNCTION [dbo].[getInvertCurrencyExchangeRateByDate](@casino_id char(16),@currency_code char(3), @end_date datetime)
RETURNS float AS
BEGIN
declare @retval float;
set @retval =
dbo.getCurrencyExchangeRateByDate(@casino_id,@currency_code,@end_date);
if (@retval != 0) return 1/@retval;
return 0;
END
CREATE FUNCTION [dbo].[getCurrencyExchangeRateByDate](@casino_id char(16),@currency_code char(3), @end_date datetime)
RETURNS float AS
BEGIN
declare @retval float;
declare @casino_curr_code char(3);
set @casino_curr_code =
(SELECT TOP 1 currency_code
FROM Casino
WHERE
casino_id=@casino_id
);
if (@currency_code = @casino_curr_code) return 1;
set @retval =
COALESCE(
(
SELECT TOP 1 exchange_rate
FROM CurrencyExchangeRateHistory
WHERE
casino_id=@casino_id and
currency_code=@currency_code AND
transact_time <= @end_date
ORDER BY
transact_time DESC
),0.0);
return @retval
END
答案 0 :(得分:2)
我很抱歉,但对于一些相当简单的事情来说,这是很多代码 我认为这满足了查询需求。
CREATE FUNCTION dbo.TVF(@casino_id char(16),@currency_code char(3), @end_date datetime)
RETURNS TABLE
AS
RETURN --IF THE JOIN FAILS OR RETURNS 0, DIVISION WILL NEVER HAPPEN AND FALL IN THE ISNULL
SELECT TOP 1 CASE WHEN A.currency_code = @currency_code THEN 1 ELSE ISNULL(1/NULLIF(B.exchange_rate,0), 0) END AS RETVAL
FROM Casino A
LEFT JOIN CurrencyExchangeRateHistory B ON A.casino_id = B.casino_id AND B.transact_time <= @end_date AND B.currency_code = A.currency_code
WHERE A.casino_id = @casino_id
ORDER BY B.transact_time DESC