De LONG para VARCHAR2

É, sei que estou bastante em falta com meu blog. O problema foi que tive que praticamente formatar meu notebook e reinstalar tudo (na verdade ainda estou reinstalando). Em casa não sobra muito tempo à noite para postar (novamente reinstalando o Vista e seus 500 patches de atualização e estudando para tirar certificação OCP). Além de ter que dividir o tempo entre os afazeres domésticos! O homem também tem que participar =P
Bem, pra não dizer que abandonei completamente meu singelo blog, vou postar sobre a única coisa que tenho visto ultimamente. Oracle Database. Recentemente tivemos uma situação na empresa que foi necessário "desfazer" a alteração do desenvolvedor. Um campo que ele havia passado para LONG, voltar a sua situação original: VARCHAR2
O problema é que não vai ser um simples ALTER TABLE que vai fazer com que tudo volte a Terra do Moranguinho. Por ser um tipo de campo usado para guardar objetos "largos", o banco não aceita que você simplesmente "diminua" o mesmo. Uma solução básica pode ser a seguinte:
1) Criar uma nova coluna do tipo destino:
ALTER TABLE tabela ADD complemento_b VARCHAR2(255);

2) Usar uma procedure como a abaixo para realizar a cópia dos dados para nova coluna:
CREATE OR REPLACE PROCEDURE long_to_varchar
AUTHID CURRENT_USER
IS
status NUMBER (5);
nSeq NUMBER(10);
vComplemento VARCHAR2(255);
BEGIN
--Alimentar a nova coluna com os dados da coluna COMPLEMENTO que é do tipo LONG
FOR reg_a IN (SELECT sequencia, complemento FROM tabela) LOOP

nSeq := reg_a.sequencia;
vComplemento := SUBSTR(reg_a.complemento,1,255);

UPDATE tabela A SET COMPLEMENTO_B = vComplemento
WHERE A.sequencia = nSeq;
END LOOP;
END;
/

3) Remover a coluna LONG:
ALTER TABLE tabela SET UNUSED COLUMN complemento;
ALTER TABLE tabela DROP UNUSED COLUMNS;
Claro, você pode simplesmente também fazer:
ALTER TABLE tabela DROP COLUMN complemento;
Mas isso pode causar um erro na aplicação dependendo do momento que seja feito.

4)Renomear a coluna:
ALTER TABLE tabela RENAME COLUMN complemento_b TO complemento;

Claro, nem tudo é um mundo feliz. Os valores que tinham mais de 255 posições serão truncados. De outro modo, pra que você queria diminuir o tamanho do campo?



Hi there! I do know that I'm very lacking with my blog. The problem was my notebook that I had to practically format it and reinstall (in fact I'm still reinstalling everything). At home I don't have so much free time at night to post (again reinstalling the Windows Vista and its more than 500 update patches, and also studying to take my OCP certify) Among that I must share my time doing some housework! Yeap, the man also must participate on that =P
Well... To not saying that I completely forgot my blog I'll post about a thing that is the main thing that I had been seeing those days: Oracle Database. Recently we had a problem at our company that was necessary to "undo" the developer implementation. A column that he had turning into LONG, back to its original structure: VARCHAR2
The big problem is that will not be a simple ALTER TABLE command that will bring you back to the Strawberry Fields land. Because it's a kind of column created to keep "large" objects, that database will not simply accept you to "decrease" the size. A basic solution I'll give you following:

1) Create a new column with the destination data type:
ALTER TABLE d_table ADD complement_b VARCHAR2(255);

2) Use a procedure like that to procede a copy of the data:
CREATE OR REPLACE PROCEDURE long_to_varchar
AUTHID CURRENT_USER
IS
status NUMBER (5);
nSeq NUMBER(10);
vComplement VARCHAR2(255);
BEGIN
--Feed the new column with the column COMPLEMENT data that is LONG type
FOR reg_a IN (SELECT seq_id, complement FROM d_table) LOOP

nSeq := reg_a.seq_id;
vComplement := SUBSTR(reg_a.complement,1,255);

UPDATE d_table A SET COMPLEMENT_B = vComplement
WHERE A.seq_id = nSeq;
END LOOP;
END;
/

3) Remove the LONG column:
ALTER TABLE d_table SET UNUSED COLUMN complement;
ALTER TABLE d_table DROP UNUSED COLUMNS;
Sure, you can simply also do:
ALTER TABLE d_table DROP COLUMN complement;
But that can bring you an application error, depending on the moment and application.

4) Rename your column:
ALTER TABLE d_table RENAME COLUMN complement_b TO complement;

Sure, not everything is a happy land. The values that had more than 255 characters will be truncate. Otherwise, why would you decrease your column size?

Comentários

  1. Maybe I should change my major to computer science just so I can understand you.

    ResponderExcluir
  2. Fuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!!!!!!!!

    ResponderExcluir

Postar um comentário

Postagens mais visitadas deste blog

CPF pra Estelionatário Ver!

Data Protector Cannot connect to the SCM (Service Control Manager)

Puff Power Daneryes