Skip to content
Advertisement

Create a View in SQL with a Concatenated Column > Then use Case Statement to affect values

I created a view with a concatenated column named DisplayName, using the code below.

create view DisplayNames as 
    select FirstName + ' ' + LastName DisplayName,
           *
    from Table1

Is there a way to change specific DisplayName values using a case statement (or a better method)

Something like:

case when DisplayName = ‘Robert Jones’ THEN ‘Bob Jones’ when DisplayName = ‘Thomas Simms’ THEN ‘Tommy Simms’

or

when FirstName = ‘Robert’ AND LastName = ‘Jones’ THEN ‘Bob Jones’

Advertisement

Answer

In SQL Server, I would suggest APPLY:

create view DisplayNames as 
    select (case when v.DisplayName = 'Bob Jones' then'Thomas Simms'
                 else v.DisplayName
            end) as DsiplayName,
           t1.*
    from Table1 t1 cross apply
         (values (FirstName + ' ' + LastName)) v(DisplayName);

This allows you to define the column in the FROM clause. Then you don’t need to figure out how to remove the old value — as would be necessary with a CTE or subquery.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement