Search code examples
sqlsql-servert-sqlsql-server-2016

Increment a Counter within a SQL SELECT Case Statement Query


I have some sample data that gives the following results:

**Name**
NULL
Bob
Steven
Jane

Susan

What should happen is the query should convert the NULLs and empty strings to a value of Anom[Counter], so it would end up like this:

**Name**
Anom1
Bob
Steven
Jane
Anom2
Susan

The basic query I have is the below, but how can I auto-increment the number?

select
    CASE WHEN Name is NULL or Name = '' THEN 'Anom1' Else Name END
from 
    Names

Sample data

Create Table Names
(
    Name varchar(50) NULL
)
insert into Names
(
    Name
)
select
    NULL
union all
select
    'Bob'
union all
select
    'Steven'
union all
select
    'Jane'
union all
select 
    ''
union all
select
    'Susan'

Solution

  • use row_number() to generate the running number and concat to concatenate it with the string Anom

    SELECT CASE WHEN [Name] IS NULL 
                  OR [Name] = '' 
                THEN CONCAT('Anom', ROW_NUMBER() OVER (PARTITION BY NULLIF([Name], '')
                                                           ORDER BY [Name]))
                ELSE [Name]
                END
    FROM   [Names]