Skip to content
Advertisement

Adding a new column to an existing table based on the contents of two preexisting columns

I am trying to add a new column to an existing table in SQL Server. I want this new column’s value to be determined based on the contents of two existing columns within the table. For example there is one column called manufacturer and another called Vendor. When the contents of these two columns are the same I would like the word ‘Same’ to be displayed in the new column, If the contents of the two columns are not the same I would like the new column to display ‘Not the Same’.

The below statement works to show me all of the values I am looking for but I am at a loss on how to add the new column as described above based on these results. I have been around the forums searching, looked into Case statements for a bit without any success.

Select *
from dbo.[Merchandise]
where [Manufacturer] = [Vendor]

Any assistance would be much appreciated.

Advertisement

Answer

I could add a column with conditions using the approach below.

 alter table TABLE_NAME
    add NEW_COL_NAME as (case 
        when COL1_NAME = COL2_NAME then 'same'
        else 'not the same'
        end);

For yours, it may like

 alter table Merchandise
    add NEW_COL_NAME as (case 
        when Manufacturer = Vendor then 'Same'
        else 'Not the Same'
        end);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement