How do i remove the dot value when there is a null value in sql

Naresh y 146 Reputation points
2022-06-09T15:45:30.593+00:00

HI i have a query where i need the remove the dot value from the first part

in the screen shoot ,field name is cust_value, and it is concatenate with the two files

field 1+ field 2

where the second field is empty i need to remove the "." value (dot value) and other values keep the dot as a separator

209889-image.png

Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

Accepted answer
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-06-09T16:05:24.627+00:00

    select field1 + case when NULLIF(field2,'') IS NOT NULL then '.' + field2 else '' end as result from dbo.myTable

    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Erland Sommarskog 122K Reputation points MVP Volunteer Moderator
    2022-06-09T20:43:38.247+00:00

    Another solution that requires SQL 2017 or later:

       concat_ws('.', field1, nullif(field2, ''))  
    

    The first parameter to concat_ws is a separator, the remaining are strings to be concatenated, separated by the separator. A NULL value will result in nothing, that is not even a separator.

    1 person found this answer helpful.
    0 comments No comments

  2. Yitzhak Khabinsky 26,586 Reputation points
    2022-06-09T16:04:39.95+00:00

    Hi @Naresh y ,

    Here is a solution that will work starting from SQL Server 2017 onwards.

    SQL

    -- DDL and sample data population, start  
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, cust_value VARCHAR(30));  
    INSERT @tbl (cust_value) VALUES  
    ('terry-01.'),  
    ('terry-02.'),  
    ('terry-01.IPL03'),  
    ('terry-02.IPL03');  
    -- DDL and sample data population, end  
      
    SELECT *   
    	, Result = TRIM('.' FROM cust_value)  
    FROM @tbl;  
    

    Output

    +----+----------------+----------------+  
    | ID |   cust_value   |     Result     |  
    +----+----------------+----------------+  
    |  1 | terry-01.      | terry-01       |  
    |  2 | terry-02.      | terry-02       |  
    |  3 | terry-01.IPL03 | terry-01.IPL03 |  
    |  4 | terry-02.IPL03 | terry-02.IPL03 |  
    +----+----------------+----------------+  
    
    0 comments No comments

  3. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-06-09T16:13:55.703+00:00
    create table test (cust_value varchar(20) )  
      
    insert into test values('Terry01.' )  
    , ('Terry01.' )  
    , ('Terry01.IPL_03' )  
    , ('Terry01.IPL_01' )  
    , ('Terry03.' )  
    , ('Terry04.' )  
       
    select   
    Case when Right(cust_value,1)='.' then reverse(stuff(reverse(cust_value),1,1,'')) else cust_value end cust_value  
    from test  
       
      
    drop table test  
    

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.