将数据插入到与外键链接的表中

时间:2012-01-13 17:41:29

标签: c# sql-server-2008 foreign-keys

首先,我尝试了这个Insert Data Into Tables Linked by Foreign Key并没有得到答案。

我有3张桌子:

表:客户

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

表:订单

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

表: OrderLine

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

我运行以下查询

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

并抛出异常

  

Order

附近的语法错误

如何在SQL Server 2008中使用外键将数据添加到表中,尤其是在这种特殊情况下?

6 个答案:

答案 0 :(得分:5)

ORDER是SQL Server中的保留关键字(用于ORDER BY操作)。

您需要用括号分隔该名称:

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

这将导致SQL Server将其视为对象名称,而不是将其作为关键字读取。

答案 1 :(得分:4)

应该是:

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

答案 2 :(得分:2)

Order是SQL中的关键字,如果您将其用作表名或列,则必须括起所有关键字。

答案 3 :(得分:0)

尝试使用此查询

INSERT INTO [Order]
( Status, CustomerID )
SELECT 13016, ID
    FROM Customers
    WHERE FirstName = 'Garderp'

答案 4 :(得分:0)

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

答案 5 :(得分:-2)

试试这个

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

如果有多个客户名称为“Gardep”,则此查询将失败。您只需要选择一条记录。使用TOP将是一个更好的主意

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