创建函数以从表中选择正确的货币字段

时间:2016-08-19 15:11:36

标签: sql function sql-server-2014

我有一些SQL,我认为我可以整理一个函数但是没有创建它们的经验。

我的代码有很多部分,如下所示:

ISNULL(SUM(Case  
when  @Currency = 'AED' And Flag = 'Current' then BILLED_AED 
when  @Currency = 'AUD' And Flag = 'Current' then BILLED_AUD 
when  @Currency = 'BRL' And Flag = 'Current' then BILLED_BRL 
when  @Currency = 'CAD' And Flag = 'Current' then BILLED_CAD
when  @Currency = 'CNY' And Flag = 'Current' then BILLED_CNY 
when  @Currency = 'EUR' And Flag = 'Current' then BILLED_EUR 
when  @Currency = 'GBP' And Flag = 'Current' then BILLED_GBP 
when  @Currency = 'HKD' And Flag = 'Current' then BILLED_HKD 
when  @Currency = 'INR' And Flag = 'Current' then BILLED_INR 
when  @Currency = 'LYD' And Flag = 'Current' then BILLED_LYD 
when  @Currency = 'QAR' And Flag = 'Current' then BILLED_QAR 
when  @Currency = 'SAR' And Flag = 'Current' then BILLED_SAR 
when  @Currency = 'SGD' And Flag = 'Current' then BILLED_SGD 
when  @Currency = 'USD' And Flag = 'Current' then BILLED_USD 
when  @Currency = 'VEF' And Flag = 'Current' then BILLED_VEF 
when  @Currency = 'ZAR' And Flag = 'Current' then BILLED_ZAR 
End),0) As Total_Billed

这使得我的代码非常长,我希望缩短。我可以创建一个函数,其中我提供@Currency参数(用户在运行报表时选择)并获取正确的BILLED值(例如)。所以我会在上面的例子中输入@Currency,@ Flag和@Field的函数' BILLED _'以正确的货币代码为后缀。

我希望这是有道理的 - 非常感谢您的任何帮助。

3 个答案:

答案 0 :(得分:0)

你可以压缩你的代码(一点点)。

isnull(sum(case Flag 
                when 'Current' then case @Currency
                      when 'AED' then BILLED_AED 
                      when 'AUD' then BILLED_AUD
                      --and so on
                      end
           end), 0) As Total_Billed

答案 1 :(得分:0)

尝试以下查询..

DECLARE @sqlCommand varchar(max)
DECLARE @Currency VARCHAR(50)='USD'
SET @sqlCommand = 'SELECT ISNULL(SUM( 
                       CASE WHEN ISNULL('+@Currency+','''')!='''' and Flag = ''Current''                    
                            THEN BILLED_'+@Currency+' END),0) AS As Total_Billed
                    FROM YourTable'

EXEC (@sqlCommand)   

答案 2 :(得分:0)

我建议您保留一张接受的货币表,以便系统可以扩展,以包含更多货币。所以你有一个像这样的表:

Table name: Accepted Currency

Currency

AED
AUD
BRL
CAD
CNY
EUR
GBP
HKD
INR
LYD
QAR
SAR
SGD
USD
VEF
ZAR

根据上表,您可以创建一个存储过程,如下所示:

CREATE PROCEDURE [dbo].[usp_CurrencySelector]
(
    @Curr VARCHAR(10)
)
AS
BEGIN

    SELECT ISNULL(CONCAT('BILLED_', [Currency]), '0')
    FROM [Accepted Currency]
    WHERE Currency = @Curr
END

仅当您根据自己的要求拥有标记和其他字段时才执行此功能。