0

What is the correct syntax to insert a data in a table that has a foreign key. I need to insert information in Purchase Details table but the column name PurchaseNo is a foreign key to the Purchases table. This is my database:

Purchase Details:

  • RefNo (PRIMARY KEY, UNIQUE)
  • PurchaseNo (FOREIGN KEY)
  • ProductID (FOREIGN KEY)
  • Quantity

Purchases:

  • PurchaseNo (PRIMARY KEY, UNIQUE)
  • SupplierID (FOREIGN KEY)
  • DatePurchased
  • DateReceived
  • ReceiptNo
  • Status

This is my goal:

My goal is to view the Product & Quantity in the right side when I clicked the add button from the left side (Inserting Supplier, Product, Quantity)

my syntax code behind is:

using (SqlConnection con = new SqlConnection(kb.GetConnection()))
{
con.Open();
string query = @"INSERT INTO PurchaseDetails VALUES (@PurchaseNo, @ProductID, @Quantity)"
}
cara jenner
  • 21
  • 1
  • 6

2 Answers2

1

You can do something like this:

SqlCommand yourCommand = new SqlCommand(@"INSERT INTO [TableName] (SelectColumns) Values " + " SELECT SomeKey, ColumnName FROM TableName WHERE YourCondition)", myConnection)
StackUseR
  • 884
  • 1
  • 11
  • 40
0

There is a no difference in syntax with or without foreign key, only thing you need to ensure with foreign key is that you need to insert data first where foreign key is being referenced.

In your case, before inserting data in purchase table, you must insert data in product and supplier table.