Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server stored procedure to insert in multiple tables [duplicate]

I have 2 tables, custlogin and custinfo:

custlogin:

custid int primary key auto notnull
custusename varchar(25)
custpassword varchar(50)

custinfo:

custid foriegnkey custlogin.custid ondelete set NULL
custfirstname varchar(25)
custlastname  varchar(25)
custaddress   varchar(100)

I want to write a stored procedure which will insert into both tables

More precisely, insert into custlogin with custusername custpassword, which would return custid for use as foreign key for custinfo.

I have searched much but I didn't find any solution.

like image 289
Sadiqabbas Hirani Avatar asked Jan 07 '14 04:01

Sadiqabbas Hirani


People also ask

Can we insert data into two tables simultaneously?

The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause.

Can we return multiple tables from stored procedure?

Yes, It is possible.


1 Answers

It will be something like below. You can use SCOPE_IDENTITY() to get the last autogenerated ID withing the scope which is this stored proc in this case:

create procedure NameOfYourProcedureHere
as
begin
SET NOCOUNT ON;
SET XACT_ABORT ON;

    insert into custlogin(custusename, custpassword) 
        values ('','') -- put values here (from parameters?)

    insert into custinfo(custid, custfirstname, custlastname, custaddress)
        values (SCOPE_IDENTITY(), '', '', '')  -- put other values here (from parameters?)

SET NOCOUNT OFF;
SET XACT_ABORT OFF;
end
like image 192
Szymon Avatar answered Sep 18 '22 11:09

Szymon