0

4 つのテーブルがあり、あるテーブルから次のテーブルに新しく挿入された pk を使用したいとします (これはすべて 1 つのバッチとして実行されます)。

declare @current_scope int;

insert into table1;
select t1.col;
set @current_scope  = select SCOPE_IDENTITY(); --this pulls table1's new row id

insert into table2;
select t1.col, t2.col from table1 t1 join table2 t2 where t2.ProductID = @current_scope ;
set @current_scope  = select SCOPE_IDENTITY(); --selects table2's new row

insert into table3;
select t2.col, t3.col  from table2 t2 join table3 t3 where t3.ProductID = @current_scope ;
set @current_scope  = select SCOPE_IDENTITY(); --selects table3's new row

insert into table4;
select t3.col, t4.col  from table3 t3 join table4 t4 where t4.ProductID = @current_scope ;

これは可能ですか?

ありがとう

4

2 に答える 2

1

テスト済みの例を次に示します。

BEGIN TRANSACTION
CREATE TABLE #t1 (id INT PRIMARY KEY IDENTITY(1,1), col1 VARCHAR(10))
CREATE TABLE #t2 (id INT PRIMARY KEY IDENTITY(100,1), t1ID INT, col2 VARCHAR(10))
CREATE TABLE #t3 (id INT PRIMARY KEY IDENTITY(200,1), t2ID INT, col3 VARCHAR(10))
CREATE TABLE #t4 (id INT PRIMARY KEY IDENTITY(300,1), t3ID INT, col4 VARCHAR(10))

DECLARE @lastID INT

INSERT #t1 ( col1 ) VALUES  ( 'A' )
SELECT @lastID = SCOPE_IDENTITY()

INSERT #t2 ( t1ID, col2) VALUES (@lastID, 'B')
SELECT @lastID = SCOPE_IDENTITY()

INSERT #t3 ( t2ID, col3) VALUES (@lastID, 'C')
SELECT @lastID = SCOPE_IDENTITY()

INSERT #t4 ( T3ID, col4) VALUES (@lastID, 'D')


SELECT * FROM #t1 T
SELECT * FROM #t2 T
SELECT * FROM #t3 T
SELECT * FROM #t4 T

ROLLBACK

出力:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)
id          col1
----------- ----------
1           A

(1 row(s) affected)

id          t1ID        col2
----------- ----------- ----------
100         1           B

(1 row(s) affected)

id          t2ID        col3
----------- ----------- ----------
200         100         C

(1 row(s) affected)

id          t3ID        col4
----------- ----------- ----------
300         200         D

(1 row(s) affected)
于 2015-11-18T23:14:57.783 に答える