I have a scalar function in my code that calls another scalar function that calls 2 other tables as detailed below. I know this must be performing like a pig. It is used throughout the database... My problem is its a little outside developing skills to rewrite this as an table valued function.
I'm attempting to win some of the developers over to rewriting the function, but we only have JAVA guys and no dedicated SQL developer, so they dont see any problems. can anyone suggest how this should be rewritten? many thanks...
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