canhanDatabase:如何将数据从非细节表移动到details-table?

时间:2015-04-08 02:46:07

标签: mysql sql-server database

过去,我有一个数据库,其中包含如下表格:

ProductID | ProductName | InStockWareHouse1 | InstockWareHouse2
---------------------------------------------------------------
1           Name1         5                   10
2           Name2         10                  20

但是现在,为了让普通用户能够自己创建更多的WareHouse,我必须切换到details-table。像这样:

产品表:

ProductID | ProductName
-----------------------
1           Name1
2           Name2
3           Name3

WareHouse表:

WareHouseID | WareHouseName
---------------------------
1             WareHouse1
2             WareHouse2
3             WareHouse3

WareHouseDetails表:

ProductID | WareHouseID | InStock
---------------------------------
1           2             5
2           2             10
2           3             10

将旧产品表中的数据移动到新的产品表并不困难,但我花了一个小时仍然没有找到将数据从旧表移动到新表的解决方案。有什么建议吗?我很好解决方案是使用查询还是自己写一个程序来读取所有数据并写回服务器,只要我不必手动重新输入所有数据。

2 个答案:

答案 0 :(得分:2)

假设您的产品ID和仓库是自动增量的,我只需要编写一个小脚本,首先将产品复制到产品表,然后手动创建仓库。最后从旧产品ID表中复制产品。注意我们需要使用SET IDENTITY_INSERT <table> ON\OFF来写入自动增量键。

类似的东西(注意我使用OldProducts作为旧产品表的名称)

SET IDENTITY_INSERT Product ON
INSERT INTO Product (ProdcutId, ProductName) SELECT ProductId, ProductName FROM OldProducts
SET IDENTITY_INSERT Product OFF

SET IDENTITY_INSERT Warehouse ON
INSERT INTO Warehouse (WarehouseId, WarehouseName) VALUES (1, 'Warehouse1')
INSERT INTO Warehouse (WarehouseId, WarehouseName) VALUES (2, 'Warehouse2')
SET IDENTITY_INSERT Warehouse OFF

INSERT INTO WarehouseDetails (ProductId, WareHouseId, InStock) SELECT ProductId, 1, InStockWarehouse1 FROM OldProducts
INSERT INTO WarehouseDetails (ProductId, WareHouseId, InStock) SELECT ProductId, 2, InStockWarehouse2 FROM OldProducts
GO

答案 1 :(得分:1)

您可以使用INSERT INTO将数据从一个表插入另一个表。

要插入Product

INSERT INTO Product(ProductID, ProductName)
    SELECT ProductID, ProductName FROM OldTable

要插入WareHouse

INSERT INTO WareHouse(WareHouseID, WareHouseName)
    SELECT 1, 'WareHouse1' UNION ALL
    SELECT 2, 'WareHouse2'

要插入WareHouseDetails

INSERT INTO WareHouseDetails(ProductID, WareHouseID, InStock)
    SELECT 
        ProductID,
        WareHouseID = 1,
        InStock = InStockWareHouse1
    FROM OldTable

    UNION ALL

    SELECT 
        ProductID,
        WareHouseID = 2,
        InStock = InStockWareHouse2
    FROM OldTable