Changing a table

0

Is it possible to change a field in a table without losing the data that was previously entered? I have a table that has a varchar field and I need to change it to int . It already has data entered of type varchar .

    
asked by anonymous 30.03.2017 / 12:38

1 answer

1

There are some approaches to what you are asking for. I suggest that you back up the table (or the database) before starting the procedures.

The following procedure is an outline and has not been tested. I suggest testing first on the development database.

nomebanco -> nome do banco de dados
tbDados -> nome da tabela
nomecoluna -> nome da coluna a alterar o tipo de dados
chaveprimaria -> coluna(s) que identifica, de forma única, cada linha da tabela

(1) The first step is to verify that the entire contents of the column can be converted from string to numeric.

-- código #1
SELECT chaveprimária. nomecoluna
  from tbDados
  where isNumeric(nomecoluna) <> 1;
go

If the above query returns any line, review the information and correct it. Only perform the next steps after you are sure that the column to be modified has numeric value (or no information - NULL) on all rows.

(2) Put the database in restricted mode.

-- código #2
ALTER DATABASE nomebanco RESTRICTED_USER;
go

(3) Create a temporary table, containing only the primary key of the table and the column to be changed, already in numeric format.

-- código #3 v3
SELECT chaveprimaria, convert(int, nomecoluna) as nomecoluna
  into tbDados2
  from tbDados;
go

(4) Change the data type of the column. Add whatever restrictions you deem necessary (for example, NOT NULL).

-- código #5
ALTER TABLE tbDados ALTER COLUMN nomecoluna int;
go

(5) Enter the information in the column, already in numeric format.

-- código #6
UPDATE T1
  set nomecoluna= T2.nomecoluna
  from tbDados as T1
       inner join tbDados2 as T2 on T1.chaveprimaria = T2.chaveprimaria;
go

(6) Verify that the conversion was successful. Making sure everything is correct, release the database and delete the temporary table.

-- código #7
DROP TABLE tbDados2;
ALTER DATABASE nomebanco MULTI_USER;
go

Suggested reading: Modify Columns

    
30.03.2017 / 13:21