You can do this by doing this:
declare @contatos table
(
ID_CONTATO_TELEFONE int,
ID_CONTATO int,
TIPO_TELEFONE varchar(1),
DDD varchar(5),
NUMERO varchar(100),
IND_SITUACAO varchar(1),
OBSERVACAO varchar(100)
)
insert into @contatos
values(1,1,'F','011','98876667','A',''),
(2,2,'F','','1198876667','A',''),
(3,3,'C','','01198876667','A',''),
(4,4,'C','','08798687667','A',''),
(5,5,'C','','(51)988765473','A',''),
(6,6,'C','','(051)98876543','A',''),
(7,7,'C','','(051)988765439 - ramal 3245','A',''),
(8,7,'C','','(051)88765439 - ramal 3245','A','');
select ID_CONTATO_TELEFONE,ID_CONTATO, TIPO_TELEFONE,
case when DDD is not null and DDD <> '' then DDD
else case when SUBSTRING(NUMERO,1,2) = '(0' then SUBSTRING(NUMERO,2,3)
when SUBSTRING(NUMERO,1,1) = '(' then ('0' +SUBSTRING(NUMERO,2,2))
when SUBSTRING(NUMERO,1,1) = '0' then SUBSTRING(NUMERO,1,3)
else ('0' +SUBSTRING(NUMERO,1,2))
end
end as DDD,
case when DDD is not null and DDD <> '' then NUMERO
else case when SUBSTRING(NUMERO,1,2) = '(0' then case when ISNUMERIC(SUBSTRING(NUMERO,6,9)) = 1 then SUBSTRING(NUMERO,6,9) else SUBSTRING(NUMERO,6,8) end
when SUBSTRING(NUMERO,1,1) = '(' then case when ISNUMERIC(SUBSTRING(NUMERO,5,9)) = 1 then SUBSTRING(NUMERO,5,9) else SUBSTRING(NUMERO,5,8) end
when SUBSTRING(NUMERO,1,1) = 0 then case when ISNUMERIC(SUBSTRING(NUMERO,4,9)) = 1 then SUBSTRING(NUMERO,4,9) else SUBSTRING(NUMERO,4,8) end
else NUMERO
end
end as NUMERO,
IND_SITUACAO, OBSERVACAO from @contatos;
Use case
and SUBSTRING
to remove the parts you need from string
.