Nuvolari
Nuvolari

Reputation: 1155

Insert data into 2 related tables at once?

I am trying to insert into two tables at once using the primary key from the first table to insert into the second but I am not sure how to go about it.

My table structure is as follows:

Person

PersonId
FirstName
Surname

Employee

EmployeeId
HoursWorked

PersonId in the Person table is an auto incremented column. EmployeeId in the second table is a primary and foreign key that should be the same as PersonId.

I been trying with this query string which I found on Google but with not much luck:

string queryString = "BEGIN TRANSACTION DECLARE @DataID int; "
 +"INSERT INTO Person(FirstName, Surname) VALUES(@firstName, @surname);" 
 + "SELECT @DataID = scope_identity();" 
 + "INSERT INTO Employee VALUES(@DataId, @hoursWorked);" 
 + "COMMIT";

Upvotes: 1

Views: 1286

Answers (2)

marc_s
marc_s

Reputation: 755541

From C#, you can try something like this:

// define the INSERT query - insert a firstname,surname into "Person",
// and insert a row into the Emplyoee table with the new ID
// created by the first insert
string insertStmt = @"BEGIN TRANSACTION
                      INSERT INTO dbo.Person(FirstName, Surname) VALUES(@FirstName, @Surname);
                      DECLARE @NewPersonId INT = SCOPE_IDENTITY();
                      INSERT INTO dbo.Employee(EmployeeId, HoursWorked) VALUES(@NewPersonId, @HoursWorked);
                      COMMIT TRANSACTION;"

// define connection and command for inserting data                       
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, conn))
{
    // Define parameters - adapt datatype and max length as required
    cmdInsert.Parameters.Add("@FirstName", SqlDbType.VarChar, 100);
    cmdInsert.Parameters.Add("@Surname", SqlDbType.VarChar, 100);
    cmdInsert.Parameters.Add("@HoursWorked", SqlDbType.Int);
    
    // set parameter values
    cmdInsert.Parameters["@FirstName"].Value = "John";
    cmdInsert.Parameters["@Surname"].Value = "Doe";
    cmdInsert.Parameters["@HoursWorked"].Value = 35;
    
    // Open connection, execute query, close connection
    conn.Open();
    
    int rowsInserted = cmdInsert.ExecuteNonQuery();
    
    conn.Close();
}

Update: as mentioned by @charlieface, you can write this code more concisely IF you're only ever inserting a single row - like this:

// define connection and command for inserting data                       
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, conn))
{
    // Define and set parameters
    cmdInsert.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = "John";
    cmdInsert.Parameters.Add("@Surname", SqlDbType.VarChar, 100).Value = "Doe";
    cmdInsert.Parameters.Add("@HoursWorked", SqlDbType.Int).Value = 35;
    
    // Open connection, execute query, close connection
    conn.Open();
    int rowsInserted = cmdInsert.ExecuteNonQuery();
    conn.Close();
}

Upvotes: 5

Charlieface
Charlieface

Reputation: 72511

You need to specify the columns you are inserting into.

You should also use SET XACT_ABORT ON if you have an explicit transaction.

Note also the use of a multi-line string.

string queryString = @"
SET XACT_ABORT ON;

BEGIN TRANSACTION;

INSERT INTO Person (FirstName, Surname)
VALUES(@firstName, @surname);
DECLARE @DataID int = scope_identity();

INSERT INTO Employee (EmployeeId, HoursWorked)
VALUES(@DataId, @hoursWorked);

COMMIT;
";

Upvotes: 5

Related Questions