插入存储过程以在SQL Server 2008中一次将数据插入到两个表中

时间:2017-06-16 08:55:25

标签: asp.net sql-server stored-procedures

如何为SQL Server 2008编写SP以将数据插入两个表

Login(username,password,id)UserInfo(id,first_name,last_name,phone_no,email,address,IsActive)

UserInfo表要求输入id,这将在插入新记录时在Login表中自动生成。我应该如何构建此SP请指导我。

3 个答案:

答案 0 :(得分:0)

您可以使用scope_identity()来捕获插入dbo.Login的id。 像这样:

drop table if exists dbo.UserInfo;
drop table if exists dbo.Login;


create table dbo.Login (
    id int not null identity (1, 1) primary key
    , username varchar(100)
    , password varchar(100)
);

create table dbo.UserInfo (
    id int not null primary key foreign key references dbo.Login(id)
    , first_name varchar(100)
    , last_name varchar(100)
    , phone_no varchar(100)
    , email varchar(100)
    , address varchar(100)
    , IsActive bit
);
go


create or alter procedure dbo.InsertIntoLoginAndUserInfo
(
    @username varchar(100)
    , @password varchar(100)
    , @first_name varchar(100)
    , @last_name varchar(100)
    , @phone_no varchar(100)
    , @email varchar(100)
    , @address varchar(100)
    , @IsActive bit
)
as

begin

    declare @id int;

    insert into dbo.Login (username, password)
    values (@username, @password);
    set @id = scope_identity();

    insert into dbo.UserInfo (id, first_name, last_name, phone_no, email, address, IsActive)
    values (@id, @first_name, @last_name, @phone_no, @email, @address, @IsActive);

end

答案 1 :(得分:0)

您可以使用SCOPE_IDENTITY()函数,该函数将返回同一范围内最后插入的标识列。

您可以在此处详细了解:SCOPE_IDENTITY (Transact-SQL)

存储过程中的代码类似于:

DECLARE @NewlyInsertedID INT
INSERT INTO Login(UserName, Password) VALUES (@UserName, @Password)
SELECT @NewlyInsertedID INT = SCOPE_IDENTITY() 

INSERT INTO UserInfo (ID, FirstName, LastName, PhoneNo, email, Address, IsActive) 
VALUES (@NewlyInsertedID, ,,, etc other columns )

答案 2 :(得分:0)

可以使用INSERT OUTPUT在一个事务中完成:

https://www.mssqltips.com/sqlservertip/2183/using-insert-output-in-a-sql-server-transaction/

/*
Demonstrate how you can insert the key values added to Staff.StaffID 
into Notifications.StaffID in single transaction
*/

INSERT INTO HR.Staff ( FirstName, LastName )
OUTPUT INSERTED.StaffID, DATEADD(d,90,GETDATE()),'90-Day Review'
INTO HR.Notification
(
StaffID,
NotificationDate,
NotificationType
)
VALUES ( 'Santa','Claus');