一次将数据插入 2 个相关表?

Insert data into 2 related tables at once?

我正在尝试使用第一个 table 的主键一次插入两个 table 以插入第二个 table 但我不确定如何去做。

我的table结构如下:

PersonId
FirstName
Surname

员工

EmployeeId
HoursWorked

PersonIdPerson table 是一个自动递增的列。第二个table中的EmployeeId是主键和外键,应该和PersonId一样。

我一直在尝试使用我在 Google 上找到的这个查询字符串,但运气不佳:

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";

在 C# 中,您可以尝试这样的操作:

// 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:如@charlieface 所述,您可以更简洁地编写此代码 IF 您只插入一行- 像这样:

// 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();
}

您需要指定要插入的列。

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;
";