-1

I have two tables

  • Employee

  • Finance

Employee contains 3 columns

  1. id
  2. Name
  3. BaseSalary

Finance table contains 2 columns

  1. id
  2. BonusPercentage

I want to add TotalBonus column in Employee table. For calculation I am using BaseSalary from Employee table and BonusPercentage from Finance table.

TotalBonus = BaseSalary + (BaseSalary * BonusPercentage)

I can use this with stored procedure but i don't want. However, I created scalar function (calculateBonus) which returns TotalBonus but the problem is that i can't add column in table as i have dependency of BonusPercentage of Finance table.

In general i want employee table to have following:

  1. id
  2. Name
  3. BaseSalary
  4. TotalBonus

I know there are many ways but want in Employee table as I am using this table on C#. Thanks

  • Can you edit the question and add the DDL, sample data, expected output and what you have tried so far all in the text format? – Suraj Kumar Feb 16 '20 at 15:59
  • How is `totalbonus` calculated? – sticky bit Feb 16 '20 at 16:06
  • TotalBonus = BaseSalary + (BaseSalary * BonusPercentage) – khawar abbasi Feb 16 '20 at 16:11
  • Maybe this SO question and answer can help you out: https://stackoverflow.com/questions/13488822/create-computed-column-using-data-from-another-table I personally would use a view instead of adding a column to the table. – Roeland Feb 16 '20 at 16:18
  • You say _"Add column"_ which means a computed column in this case, so the short answer is _You can't_ because you're not allowed to use a column from other tables in a computed column. Instead you may create a view (which I recommend), or create a user-defined function to get the results. – Ilyes Feb 16 '20 at 17:27

1 Answers1

0

Assuming that there can be a maximum of one row in finance for each employee, you want a (left) join:

SELECT e.id,
       e.name,
       e.basesalary,
       coalesce(f.bonuspercentage, 0) * e.basesalary totalbonus
       FROM employee e
            LEFT JOIN finance f
                      ON f.id = e.id;
sticky bit
  • 36,626
  • 12
  • 31
  • 42