我有两个表“user info”和“user login”,它们都有一个ID列,但是user info表中的ID列是一个标识类型,用户登录表的ID列引用了ID用户信息表。
这是我的存储过程,它同时向两个表插入值。
CREATE PROCEDURE [dbo].[InsertUser]
@fname varchar(50),
@lname varchar(50),
@gender int,
@bday date,
@address varchar(max),
@city varchar(50),
@zip nvarchar(50),
@country varchar(50),
@status int,
@telhome varchar(50),
@teloff varchar(50),
@mobile varchar(50),
@login varchar(50),
@pass varchar(50),
@email varchar(50),
@pin varchar(50)
AS
INSERT INTO UserInfo
(
Firstname,
Lastname,
Gender,
Birthday,
[Address],
City,
Zip,
Country,
Civil,
HomeTelephone,
OfficeTelephone,
MobileTelephone)
VALUES (@fname, @lname, @gender,
@bday, @address, @city, @zip, @country, @status, @telhome, @teloff, @mobile)
INSERT INTO UserLogin
(
ID,
[Login],
[Password],
Email,
TransPIN
)
VALUES (***THE ID OF NEW UserInfo row**, @login, @pass, @email, @pin)
我的问题是我必须将用户信息表中新插入的行生成的ID插入用户登录表中。
答案 0 :(得分:2)
将最后插入的Id分配给变量“SET @lastInsertedId = SCOPE_IDENTITY()”并在第二个插入语句中使用此变量。
CREATE PROCEDURE [dbo].[InsertUser]
@fname varchar(50),
@lname varchar(50),
@gender int,
@bday date,
@address varchar(max),
@city varchar(50),
@zip nvarchar(50),
@country varchar(50),
@status int,
@telhome varchar(50),
@teloff varchar(50),
@mobile varchar(50),
@login varchar(50),
@pass varchar(50),
@email varchar(50),
@pin varchar(50)
AS
DECLARE @lastInsertedId INT;
INSERT INTO UserInfo
(
Firstname,
Lastname,
Gender,
Birthday,
[Address],
City,
Zip,
Country,
Civil,
HomeTelephone,
OfficeTelephone,
MobileTelephone)
VALUES (@fname, @lname, @gender,
@bday, @address, @city, @zip, @country, @status, @telhome, @teloff, @mobile)
SET @lastInsertedId = SCOPE_IDENTITY()
INSERT INTO UserLogin
(
ID,
[Login],
[Password],
Email,
TransPIN
)
VALUES (@lastInsertedId, @login, @pass, @email, @pin)
答案 1 :(得分:0)