2011-06-08 66 views
3

我的代碼中有一個標量函數,它調用另一個標量函數,調用2個其他表,如下所述。我知道這必須像豬一樣表現。它被用於整個數據庫...我的問題是它有一點在外部開發技能,將其重寫爲表值函數。sql標量函數

我試圖贏得一些開發人員重寫函數,但我們只有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 
[email protected]_id 
); 

if (@currency_code = @casino_curr_code) return 1; 

set @retval = 
COALESCE(
(
SELECT TOP 1 exchange_rate 
FROM CurrencyExchangeRateHistory 
WHERE 
[email protected]_id and 
[email protected]_code AND 
transact_time <= @end_date 
ORDER BY 
transact_time DESC 
),0.0); 

return @retval 
END 
+0

哪個版本的SQL Server? – Yuck 2011-07-21 11:57:31

回答

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