2014-10-11 146 views
-1

我試圖在新數據庫中創建幾個表,但是當我嘗試創建它們時,會創建一對錯誤。我目前正在使用Microsoft SQL Server Management Studio。在SQL中創建表時出錯

錯誤似乎是在我試圖爲外鍵添加約束的代碼的末尾。任何幫助將不勝感激,謝謝。

下面是代碼,它是爲了生成3個表,其中1個表包含2個具有匹配列名的表的外鍵。

CREATE TABLE Customers 
(
    CustomerID INT NOT NULL PRIMARY KEY IDENTITY, 
    ContactName VarChar(50) NULL, 
    Company VarChar(45) NULL, 
    Phone VarChar(12) NULL, 
) 

CREATE TABLE Shippers 
(
    ShipperID INT NOT NULL PRIMARY KEY IDENTITY, 
    Company VarChar(45) NULL, 
    Phone VarChar(12) NULL, 
) 

CREATE TABLE Orders 
(
    OrderID INT NOT NULL PRIMARY KEY IDENTITY, 
    OrderDate DATETIME NULL, 
    ShippedDate DATETIME NULL, 
    ShipperID INT NULL, 
    Freight  DECIMAL NULL, 
    CustomerID INT NULL, 

    CONSTRAINT fk_Orders_Shippers 
     FOREIGN KEY ShipperID 
     REFERENCES Shippers(ShipperID) 
      ON DELETE NO ACTION 
      ON UPDATE NO ACTION 
    CONSTRAINT fk_Orders_Customers 
     FOREIGN KEY CustomerID 
     REFERENCES Customers(CustomerID) 
      ON DELETE NO ACTION 
      ON UPDATE NO ACTION 
) 

而這些都是我得到的錯誤:

消息102,級別15,狀態1,行21
附近有語法錯誤 'ShipperID'。

Msg 102,Level 15,State 1,Line 23
'ACTION'附近語法不正確。

Msg 102,Level 15,State 1,Line 28
'ACTION'附近的語法不正確。

任何想法是什麼問題?

回答

4

由於缺少括號,錯誤消息指向一對多餘的逗號,缺少逗號和不正確的外鍵語法。

這是正確的版本:

CREATE TABLE Customers (
    CustomerID INT NOT NULL PRIMARY KEY IDENTITY, 
    ContactName VarChar(50) NULL, 
    Company VarChar(45) NULL, 
    Phone  VarChar(12) NULL       -- SURPLUS COMMA REMOVED 
    ) 

CREATE TABLE Shippers (
    ShipperID INT NOT NULL PRIMARY KEY IDENTITY, 
    Company VarChar(45) NULL, 
    Phone  VarChar(12) NULL       -- SURPLUS COMMA REMOVED 
    ) 


CREATE TABLE Orders (
    OrderID  INT NOT NULL PRIMARY KEY IDENTITY, 
    OrderDate DATETIME NULL, 
    ShippedDate DATETIME NULL, 
    ShipperID INT NULL, 
    Freight  DECIMAL NULL, 
    CustomerID INT NULL, 
     CONSTRAINT fk_Orders_Shippers 
      FOREIGN KEY (ShipperID)       -- PARENTHESES ADDED 
      REFERENCES Shippers(ShipperID) 
      ON DELETE NO ACTION 
      ON UPDATE NO ACTION 
      ,             -- COMMA ADDED 
     CONSTRAINT fk_Orders_Customers 
      FOREIGN KEY (CustomerID)      -- PARENTHESES ADDED 
      REFERENCES Customers(CustomerID) 
      ON DELETE NO ACTION 
      ON UPDATE NO ACTION 
    ) 
+0

+1從我身邊很好的解釋。 – radar 2014-10-11 01:55:38