Search code examples
sqlsql-servert-sqlreplacenvarchar

Replacing values in a nvarchar(50) column


I have a column in my SQL Server table that is a nvarchar(50). I'm looking for a way to replace values in the column.

So for example, This is my column with the original values:

attached

What I want is for each value to equal the following value:

please see second picture to see the required outputs

I can get this working with a replace function, however it then moves it to a new column for each value I'm replacing. Ideally what I would like is to have a single column with my new changes.

I cannot use the update function as I only have read access to this table.

Any info would be great.

Thanks.


Solution

  • Sample data

    create table MyTable
    (
      Task nvarchar(50)
    );
    
    insert into MyTable (Task) values
    ('VLV LOADING/RELEASE 1st DS'),
    ('VLV LOADING/RELEASE 2nd DS'),
    ('VLV LOADING/RELEASE 3rd DS'),
    ('VLV LOADING/RELEASE 1st DS'),
    ('VLV LOADING/RELEASE 2nd DS'),
    ('VLV LOADING/RELEASE 3rd DS');
    

    Solution

    Option 1

    Using a case expression.

    select case mt.Task
             when 'VLV LOADING/RELEASE 1st DS' then 'Proximal Release Force-S'
             when 'VLV LOADING/RELEASE 2nd DS' then 'Proximal Release Force-L'
             when 'VLV LOADING/RELEASE 3rd DS' then 'Proximal Release Force-M'
           end as Task
    from MyTable mt;
    

    Option 2

    In case the replacement values are available in another table, then use a join.

    create table Task
    (
      Id int,
      Task nvarchar(50),
      Description nvarchar(50)
    );
    
    insert into Task (Id, Task, Description) values
    (10, 'VLV LOADING/RELEASE 1st DS', 'Proximal Release Force-S'),
    (11, 'VLV LOADING/RELEASE 2nd DS', 'Proximal Release Force-M'),
    (12, 'VLV LOADING/RELEASE 3rd DS', 'Proximal Release Force-L');
    
    select t.Description as Task
    from MyTable mt
    join Task t
      on t.Task = mt.Task;
    

    Result

    Task
    ------------------------
    Proximal Release Force-S
    Proximal Release Force-M
    Proximal Release Force-L
    Proximal Release Force-S
    Proximal Release Force-M
    Proximal Release Force-L
    

    Fiddle to see things in action.