如何使用SQL将表拆分为多个表

时间:2013-12-18 02:10:48

标签: sql sql-server

嗨,我有这张桌子汽车:

MODEL nvarchar(20)
STYLE nvarchar(20)
ENGINE nvarchar(5)
CAPACITY smallint
MAX_SPEED smallint
PRICE smallmoney
MARKET nvarchar(20)
COMPETITOR nvarchar(20)

我想通过SQL查询将其拆分为3个表:

汽车:

MODEL nvarchar(20)
STYLE nvarchar(20)
MAX_SPEED smallint
PRICE smallmoney

发动机:

ENGINE nvarchar(5)
CAPACITY smallint

市场:

MARKET nvarchar(20)
COMPETITOR nvarchar(20)

徘徊是如何使用sql命令完成的,谢谢

4 个答案:

答案 0 :(得分:2)

最简单的方法。选择...将创建新表:

SELECT DISTINCT
    ENGINE,
    CAPACITY
INTO Engine
FROM CARS


SELECT DISTINCT
    MARKET,
    COMPETITOR
INTO Market
FROM CARS

然后从原始表中删除已解散的列。例如

ALTER TABLE Cars DROP COLUMN ENGINE
ALTER TABLE Cars DROP COLUMN CAPACITY
ALTER TABLE Cars DROP COLUMN MARKET
ALTER TABLE Cars DROP COLUMN COMPETITOR

这将特别针对您的要求。但是,我不确定这是你想要的 - 然后没有汽车参考引擎或市场细节 - 所以信息丢失了。

如果“ENGINE”和“MARKET”定义了新表的键,我建议将这些列保留在car表上作为外键。例如,只有DROP容量和竞争对手。

您也可以在新表上创建主键。例如:     ALTER TABLE引擎添加约束[PK_Engine]主键簇发动机ASC

答案 1 :(得分:1)

运行这个....

create table Engine
(
    EngineId int identity(1,1) not null primary key,
    Engine nvarchar(5) not null,
    Capacity smallint not null
)
go

insert into Engine
(Engine, Capacity)
(select distinct Engine,Capacity from Cars)
go

alter table Cars
add EngineId int null
go

update Cars
set Cars.EngineId = e.EngineId
from Engine e where  e.Engine = Cars.Engine
go


create table Market
(
    Id int identity(1,1) not null primary key,
    Market nvarchar(20) not null,
    Competitor nvarchar(20) not null
)
go

insert into Market
(Market, Competitor)
(select distinct Market,Competitor from Cars)
go

alter table Cars
add MarketId int null
go

update Cars
set Cars.MarketId = m.MarketId
from Market m where  m.Market = Cars.Market
go


alter table Cars
drop column Market;


alter table Cars
drop column Competitor;


alter table Cars
drop column Engine;


alter table Cars
drop column Capacity;

答案 2 :(得分:0)

是的,它是可能的,它被称为"规范化"。

答案 3 :(得分:0)

要规范化这些表,首先需要create个新表,将SQL写入insert数据到新表中,然后alter原始表。

参见http://technet.microsoft.com/en-us/library/ms174979.aspxhttp://technet.microsoft.com/en-us/library/dd776381(v=sql.105).aspxhttp://msdn.microsoft.com/en-us/library/ms190273.aspx