Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data into tables linked with foreign key

First of all I tried this Insert Data Into Tables Linked by Foreign Key and didn't get the answer.

I have 3 tables:

Table: Customers

ID -------LastName-------FirstName-------PhoneNumber

Table: Order

ID-------Status-------CustomerID

Table: OrderLine

ID-------OrderID-------Product-------Quantity-------PricePerUnit

I run the following query

SqlCommand myCommand2 = 
   new SqlCommand(@"INSERT INTO Order (Status, CustomerID) 
                    VALUES(13016, SELECT ID FROM Customers WHERE FirstName = 'Garderp')", 
                  myConnection);`

and it throws exception

Syntax error near Order

How can I add data into table with foreign key in SQL Server 2008 especially in this particular case?

like image 458
Bip Avatar asked Nov 28 '25 17:11

Bip


2 Answers

It should be:

SqlCommand myCommand2 = new SqlCommand(@"INSERT INTO [Order] (Status, CustomerID) " 
   + " SELECT 13016, ID 
       FROM Customers 
       WHERE FirstName = 'Garderp')"
, myConnection);
like image 69
Icarus Avatar answered Nov 30 '25 07:11

Icarus


ORDER is a reserved keyword in SQL Server (used in the ORDER BY operation).

You need to delimit that name with brackets:

"INSERT INTO [Order] (Status, CustomerID) VALUES "

That will cause SQL Server to treat it as an object name instead of reading it as a keyword.

like image 33
JNK Avatar answered Nov 30 '25 05:11

JNK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!