简体   繁体   English

使用参数化查询将自动生成的ID插入ForeignKey列

[英]Insert Auto-Generated ID Into ForeignKey Column Using Parametrized Queries

Unsure how to approach this using SQL parametrized queries. 不确定如何使用SQL参数化查询来解决此问题。 I can currently insert data (a customer in this scenario) into an SQL table and let the database generate and handle the primary key ID's rather than insert an ID manually along with the rest of the attributes. 我目前可以将数据(在这种情况下为客户)插入SQL表中,并让数据库生成和处理主键ID,而不是手动将ID与其余属性一起插入。

My question is how would I insert this auto-generated ID into another table to it's related foreign-key column using parametrized queries? 我的问题是,如何使用参数化查询将此自动生成的ID插入与其相关的外键列的另一个表中? An example would be if the second table was for bookings and it had to get the ID value (Customer table) of the customer who made the booking and insert it into the FK ID column in the Booking table. 例如,如果第二张表用于预订,并且它必须获取进行预订的客户的ID值(客户表),然后将其插入到Booking表的FK ID列中。

I have looked at code online and on Stack Overflow and it isn't quite what I am looking for as they are either using SQL procedures in the database designer or dealing with manually inserted ID's. 我已经在网上和Stack Overflow上查看了代码,它们并不是我想要的,因为它们要么在数据库设计器中使用SQL过程,要么处理手动插入的ID。

Example code I wrote: 我写的示例代码:

//Insert CustomerID into TestTable
public void AddCustomerIdToForeignKeyColumnInNewTable()
{
    string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

    SqlConnection myConnection = new SqlConnection(connectionString);

    String query;

    query = "INSERT INTO TestTable VALUES (@CustomerID)";
    SqlCommand dbCommand = new SqlCommand(query, myConnection);
    dbCommand.Parameters.AddWithValue("@CustomerID", whateverIdValueGoesHere);
    try
    {
        myConnection.Open();
        dbCommand.ExecuteNonQuery();
        myConnection.Close();
    }
    catch (Exception ex)
    {
        Exception e = ex;
        myConnection.Close();
    }

}

You can use: 您可以使用:

 Select SCOPE_IDENTITY(); 

Right after the insert statement. 在插入语句之后。

In other words: 换一种说法:

query = "INSERT INTO TestTable VALUES (@CustomerID); SELECT SCOPE_IDENTITY();";

And then: 接着:

 var cid= dbCommand.ExecuteScalar();

cid will contain the value of the Customer ID generated by the database cid将包含数据库生成的客户ID的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM