Застрявшая попытка переместить две таблицы от одного DB до другого DB

Просто объедините файлы.

cat jquery.js >> a_javascript_file.js

Или, так как вы, вероятно, хотите сначала jQuery:

cat a_javascript_file.js jquery.js > tmp.js;
mv tmp.js a_javascript_file.js
6
задан Muntasir 8 April 2019 в 06:54
поделиться

7 ответов

Я думаю, вам нужно сделать это в два этапа.

Вам нужно импортировать старые таблицы и сохранить старые идентификаторы (и сгенерировать новые). Затем, когда они находятся в новой базе данных и у них есть как новые, так и старые идентификаторы, вы можете использовать старые идентификаторы, чтобы связать новые идентификаторы, затем вы отбрасываете старые идентификаторы.

Вы можете сделать это, импортировав во временные (т.е. они будут выброшены), затем вставка в постоянные таблицы, исключая старые идентификаторы.

Или импортируйте напрямую в новые таблицы (с измененной схемой, чтобы также содержать старые идентификаторы), а затем отбросить старые идентификаторы, когда они '

РЕДАКТИРОВАТЬ:

Хорошо, я немного понимаю, что вы ищете, благодаря комментариям здесь и другим ответам. Я придумал это, думаю, он будет делать то, что вы хотите.

В основном без курсоров он проходит через родительскую таблицу, I tried it out and it should work, it doesn't need exclusive access to the tables and should be orders of magniture faster than a cursor.

declare @oldId as int
declare @newId as int

select @oldId = Min(ParentId) from OldTable1 

while not @oldId is null
begin
    Insert Into NewTable1 (Name)
    Select Name from OldTable1 where ParentId = @oldId

    Select @newId = SCOPE_IDENTITY()

    Insert Into NewTable2 (ParentId, Foo)
    Select @newId, Foo From OldTable2 Where ParentId = @oldId

    select @oldId = Min(ParentId) from OldTable1 where ParentId > @oldId

end

Hope this helps,

4
ответ дан 17 December 2019 в 04:51
поделиться

Можете ли вы изменить схему старых таблиц? Если это так, вы можете поместить столбец «новый идентификатор» в старые таблицы и использовать его в качестве ссылки.

Возможно, вам придется выполнить построчную вставку в новую таблицу, а затем получить scope_identity, сохранить его в старый table1. Но для таблицы 2 вы можете присоединиться к старой таблице 1 и получить new_id.

0
ответ дан 17 December 2019 в 04:51
поделиться

Well, I guess you'll have to determine other criteria to create a map like oldPK => newPK (for example: Name field is equal?

Then you can determine the new PK that matches the old PK and adjust the ParentID accordingly.

You may also do a little trick: Add a new column to the original Table1 which stores the new PK value for a copied record. Then you can easily copy the values of Table2 pointing them to the value of the new column instead of the old PK.

EDIT: I'm trying to provide some sample code of what I meant by my little trick. I'm not altering the original database structure, but I'm using a temporary table now.

OK, you might try to following:

1) Create temporary table that holds the values of the old table, plus, it gets a new PK:

CREATE TABLE #tempTable1
(
    newPKField INT,
    oldPKField INT,
    Name VARCHAR(50)
)

2) Insert all the values from your old table into the temporary table calculating a new PK, copying the old PK:

INSERT INTO #tempTable1
SELECT
   newPKValueHere AS newPKField,
   ParentID as oldPKField,
   Name
FROM
   Table1

3) Copy the values to the new table

INSERT INTO NewTable1
SELECT
   newPKField as ParentId,
   Name
FROM
   #tempTable1

4) Copy the values from Table2 to NewTable2

INSERT INTO NewTable2
SELECT
   ChildID,
   t.newPKField AS ParentId,
   Foo
FROM 
   Table2
   INNER JOIN #tempTable1 t ON t.ParentId = parentId

This should do. Please note that this is only pseudo T-SQL Code - I have not tested this on a real database! However, it should come close to what you need.

1
ответ дан 17 December 2019 в 04:51
поделиться

First of all - can you not even have some temporary schema that you can later drop?! That would make life easier. Assuming you can't:

If you're lucky (and if you can guarantee that no other inserts will be happening at the same time) then when you insert the Table1's data into your new table you could perhaps cheat by relying on the sequential order of the inserts.

You could then create a view that joins the 2 tables on a row-count so that you have a way to correlate the keys to each other. That way you'd be one step closer to being able to identify the 'ParentId' for the new Table2.

0
ответ дан 17 December 2019 в 04:51
поделиться

I had the wonderful opportunity to be dug deep in migration scripts last summer. I was using Oracle's PL/SQL for the task. But you did not mention what technology are you using? What are you migrating the data into? SQL Server? Oracle? MySQL?

The approach is to INSERT a row from table1 RETURING the new primary key generated (probably by a SEQUENCE [in Oracle]) and then INSERT the dependent records from table2, changing their foreign key value to the value returned by the first INSERT. Can't help you any better unless you can specify what DBMS are you migrating data into.

0
ответ дан 17 December 2019 в 04:51
поделиться

Из вашего вопроса я не уверен, какое программное обеспечение базы данных вы используете, но если временные таблицы являются вариантом, создайте временную таблицу, содержащую исходный первичный ключ table1 и новый первичный ключ таблицы1. Затем создайте другую временную таблицу с копией table2, обновите копию, используя таблицу «старый ключ, новый ключ», которую вы создали ранее, затем используйте «вставить в выбор из» (или любую другую соответствующую команду для вашей базы данных), чтобы скопировать пересмотренный временный стол в его постоянное местоположение.

0
ответ дан 17 December 2019 в 04:51
поделиться

The following Pseudo-ish code should work for you

CREATE TABLE newtable1
  ParentId INT PK
  OldId   INT
  Name     VARCHAR(50)

CREATE TABLE newtable2
  ChildId    INT pk
  ParentId   INT FK
  OldParent  INT
  Foo        VARCHAR(50)   

  INSERT INTO newtable1(OldId, Name)
  SELECT  ParentId, Name FROM oldtable1

  INSERT INTO newtable2(OldParent, Foo)
  SELECT ParentId, Foo FROM oldtable2

UPDATE newtable2 SET ParentId = (
  SELECT n.ParentId 
  FROM   newtable1 AS n
  WHERE  n.OldId = newtable2.oldParent
)

ALTER TABLE newtable1 DROP OldId
ALTER TABLE newtable2 DROP OldParent
0
ответ дан 17 December 2019 в 04:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: