使用@@identity 进行连续插入
Using @@identity for consecutive inserts
我有这种情况,
INSERT INTO TABLE1()...
--Get the primary key from the above insert
SELECT @@identidy
INSERT INTO TABLE2()...
自动生成的主键必须是 TABLE 中的外键 2. 如何构造我的第二个 INSERT 以具有 @@identity 的值?
这好像不行,
INSERT INTO TABLE1 (user_id, name) (@@identity, 'ABC')
我收到一条错误消息 Must declare variable '@@identidy'.
干杯!!
1) 你拼写 @@identity
错误 (@@identidy
)
2) 您应该创建一个局部变量 (@LastIdentity
) 以在第一次插入后立即存储最后插入的标识。然后将该变量用作第二个 INSERT
:
的输入
DECLARE @LastIdentity int
INSERT INTO TABLE1()...
--Get the primary key from the above insert
SELECT @LastIdentity = @@identity
INSERT INTO TABLE2(...) VALUES (@LastIdentity, ...
我有这种情况,
INSERT INTO TABLE1()...
--Get the primary key from the above insert
SELECT @@identidy
INSERT INTO TABLE2()...
自动生成的主键必须是 TABLE 中的外键 2. 如何构造我的第二个 INSERT 以具有 @@identity 的值?
这好像不行,
INSERT INTO TABLE1 (user_id, name) (@@identity, 'ABC')
我收到一条错误消息 Must declare variable '@@identidy'.
干杯!!
1) 你拼写 @@identity
错误 (@@identidy
)
2) 您应该创建一个局部变量 (@LastIdentity
) 以在第一次插入后立即存储最后插入的标识。然后将该变量用作第二个 INSERT
:
DECLARE @LastIdentity int
INSERT INTO TABLE1()...
--Get the primary key from the above insert
SELECT @LastIdentity = @@identity
INSERT INTO TABLE2(...) VALUES (@LastIdentity, ...