How to remove data from a column where there is no number

sujith kumar matharasi 351 Reputation points
2020-10-13T16:14:57.823+00:00

Hi All,

I have a column which has sample values such as

Column1
abc
abc1
123

I would like to have the output as :

column1

abc1
123

I would like to replace blank for where there is only text and no number in the column.

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Stefan Hoffmann 621 Reputation points
    2020-10-13T16:54:54.4+00:00

    Use LIKE or PATINDEX with an number detection pattern:

    DECLARE @Table TABLE (
        Column1 NVARCHAR(255)
    );
    
    INSERT INTO @Table ( Column1 )
    VALUES ( N'abc' ) ,
           ( N'abc1' ) ,
           ( N'123' );
    
    SELECT *
    FROM   @Table T
    WHERE  PATINDEX('%[0-9]%', T.Column1) > 0;
    
    SELECT *
    FROM   @Table T
    WHERE  T.Column1 LIKE '%[0-9]%';
    
    DELETE @Table
    WHERE NOT Column1 LIKE '%[0-9]%';
    
    SELECT *
    FROM   @Table T;
    

    Then your desired result is found by negating it.


1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 26,586 Reputation points
    2020-10-13T17:27:08.093+00:00

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Col NVARCHAR(255));
    INSERT INTO @tbl (Col) VALUES 
    (N'abc'),
    (N'abc1'),
    (N'123');
    -- DDL and sample data population, end
    
    SELECT ID, Col AS [Before]
        , IIF(PATINDEX('%[0-9]%', Col) > 0, col,'') AS [After]
    FROM @tbl;
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.