如何将列从一个表移动到新表?

时间:2012-09-01 18:17:20

标签: sql sqlite refactoring

我想通过将一个表分成两个来重构我的数据库。我想将一些现有列移动到新表中。例如,假设我想将下面address表中的Employee字段移动到新的Address表。

如何使用sqlite (或等效的SQL)来完成

之前:

Employee Table
   employee_id (Primary)
   name
   address
   city

后:

Employee Table
   employee_id (Primary)
   name
   address_id

Address Table
   address_id (Primary)
   address
   city

3 个答案:

答案 0 :(得分:1)

create table employee_new(employee_id,name,address_id);
insert into employee_new select employee_id,name,employee_id from employee;
create table address(address_id,address,city);
insert into address select employee_id,address,city from employee; 
alter table employee rename to employee_old;
alter table employee_new rename to employee;

答案 1 :(得分:1)

试试这个:

  CREATE TABLE Employee(
  emp_id int,
  name nvarchar(50),
  address nvarchar(50),
  city nvarchar(50),
  PRIMARY KEY (emp_Id));

ALTER TABLE Employee
ADD address_id int NOT NULL IDENTITY;

INSERT INTO EMPLOYEE(emp_id,name,address,city) VALUES (111,'JOHN','XXX STREET','XYZ');

CREATE TABLE Address(
   address_id int NOT NULL,
   address nvarchar(100),
   city nvarchar(100),
   PRIMARY KEY (address_id)
  );

INSERT INTO Address (address_id, address, city)
SELECT address_id, address, city
FROM Employee;

ALTER TABLE Employee
DROP COLUMN address;

ALTER TABLE Employee
DROP COLUMN city;

检查here

答案 2 :(得分:0)

1:在第一个表格中创建AddressID列并指定一个数字 2:将新表空创建。
3:传输数据(类似这样)
        插入地址(ADDRESS_ID,ADDRESS,CITY)
        从员工中选择ADDRESS_ID,ADDRESS,CITY 4:从第一个表中删除旧列并创建外键