title: Create Function to select correct currency field from a table
body: <p>I have some SQL that I think I could tidy up with a function but am not experienced in creating them.</p>
  
  <p>My code has many sections that all look as follows:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>This makes my code massively long and I'm hoping to shorten.  Can I create a function where I provide the @Currency parameter (that the user has selected when running the report) and get the correct BILLED value (for example).  So I would input into the function the @Currency, @Flag and @Field - in the example above 'BILLED_' to be suffixed with the right currency code.</p>
  
  <p>I hope this makes sense - many thanks in advance for any help.</p>