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?
It should be:
SqlCommand myCommand2 = new SqlCommand(@"INSERT INTO [Order] (Status, CustomerID) "
+ " SELECT 13016, ID
FROM Customers
WHERE FirstName = 'Garderp')"
, myConnection);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With