0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLServerでIdentityが設定されているテーブルをコピーする方法

Posted at

SQLServerで本番環境DBのテーブルデータを、テスト環境DBのテーブルにコピーする事になった。
その際、対象テーブルにIdenityが設定されていた場合、普通にコピーすると採番が再設定されてしまうので
下記の方法で対応した。

table_1 → コピー元テーブル
table_2 → コピー先テーブル
field_1 → フィールド1
filed_2 → フィールド2

【作業その1 フィールド名取得】
SELECT * FROM syscolumns
WHERE id = object_id('table_1')

【作業その2 コピー先テーブルのトランケート】
TRUNCATE TABLE table_2

【作業その3 コピー】
SET IDENTITY_INSERT table_2 ON
INSERT INTO 
table_2
(
field_1,
field_2,
.
.
.
)
SELECT * FROM tabke_1;
SET IDENTITY_INSERT table_2 OFF
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?