2

I have a table with name table1 containing:

col1
a.b

1.1
2.2
3.3
1.3
2.3

enter image description here

I want compare left character of dot (a) with right character of dot (b), and if a = b, remove .b.

So table1 must be changed to this:

col1
a.b

1
2
3
1.3
2.3

enter image description here

Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
xxxsenatorxxx
  • 121
  • 2
  • 13
  • 1
    try to split the col first (http://stackoverflow.com/questions/10581772/how-to-split-a-comma-separated-value-to-columns), and then compare them – Prisoner Sep 09 '16 at 09:30

2 Answers2

2

Try this:

DECLARE @tbl1 as TABLE(
   Id  INT,
   col1  VARCHAR(20)
)

INSERT INTO @tbl1 VALUES(1,'1.1')
INSERT INTO @tbl1 VALUES(2,'2.2')
INSERT INTO @tbl1 VALUES(3,'3.3')
INSERT INTO @tbl1 VALUES(4,'1.3')
INSERT INTO @tbl1 VALUES(5,'1.4')

SELECT
    Id,
    CASE WHEN SUBSTRING(col1,0,CHARINDEX('.',col1))=SUBSTRING(col1,CHARINDEX('.',col1)+1,len(col1))
    THEN SUBSTRING(col1,0,CHARINDEX('.',col1))
    ELSE col1
    END
FROM
@tbl1

UPDATE:

UPDATE @tbl1 
    SET col1=SUBSTRING(col1,0,CHARINDEX('.',col1))
WHERE SUBSTRING(col1,0,CHARINDEX('.',col1))=SUBSTRING(col1,CHARINDEX('.',col1)+1,len(col1))
0

I would write the update as:

with toupdate as (
      select t1.*,
             left(t1.col1, charindex('.', t1.col1 + '.') - 1) as firstpart
      from table1 t1
     )
update toupdate
     set col1 = firstpart
     where col1 = firstpart + '.' + firstpart;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786