菊花链多个scope_identities?

时间:2015-11-18 22:23:51

标签: sql sql-server-2012 scope-identity

假设我有4个表,我想使用从一个表到下一个表的新插入的pk(这一切都作为一个批处理执行)

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 ;

这可能吗?

由于

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

这是我修改后的代码,用于查看其使用方式:

usr/local/var/lib/cassandra/commitlog/