jonny jonny - 4 years ago 141
SQL Question

Is it possible to insert data to 2 tables from 1 controller?

Here is my database. I want to make a stored procedure to insert data into the Reservation table. I want to insert room_id, data check-in and other fields but instead of guest_id I want to put first name, last name, Phone and other fields from the Guest table. Is this possible?

enter image description here

Answer Source

I would create 2 stored procedures. one for saving the guest info and one for saving the reservation info.

CREATE PROCEDURE SaveGuest(@firstName varcahr(50),@lastName varchar(50),@phone varchar(15))
AS
 BEGIN

    INSERT INTO Guest(FirstName,LastName,Phone) VALUES (@firstName,@lastName,@phone);
    RETURN SCOPE_IDENTITY()

 END

Procedure to call Second Proc

CREATE PROCEDUE SaveReservation(@roomId int,@guestId int,@price decimal)
AS
 BEGIN
   INSERT INTO Reservation(Room_ID,Guest_ID,Price) VALUES (@roomID,@guestId,@price)
   RETURN SCOPE_IDENTITY()
 END

This is a sample. You need to add field for all your db columns which is not null.

Now create 2 methods to save these data. SaveGuest and SaveReservation. Return the Newly Saved Guest ID from your SaveGuest method. Now in your action method call, the SaveGuest method first. check the return value of the method. If it is a valid number, That means the guest info is saved. USe that Guest ID in saving the Second part (Reservation); Something like this

public ActionResult SAve(YourViewMolde model)
{
int guestId=  SaveGuest("john","alex",....);
if(guestID>0)
 {
   SaveReservation(guestId,34,...);
 }
 else
 {
   model.AddModelError("","Error in saving Guest info!");
 }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download