SQL Server错误' TABLE'的错误语法约束

时间:2014-11-04 14:43:18

标签: sql-server

我将在接下来的几周内完成一个SQL作业,我有一个小错误,我似乎无法找到。

USE master

GO

IF EXISTS (SELECT name
    FROM sysdatabases
    WHERE name = 'travel')
    DROP DATABASE travel
    GO
    CREATE DATABASE travel
GO

USE travel
GO

CREATE TABLE customer
(
    customerID INT,
    lastname VARCHAR(70) NOT NULL,
    firstname VARCHAR(70) NOT NULL,
    phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
    category VARCHAR(7) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
    CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),

    CONSTRAINT customerPK
        PRIMARY KEY (customerID)
)

CREATE TABLE package    /*Still need to do the Zero Padding*/
(
    packageCode VARCHAR(6),
    destination VARCHAR(70),
    CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
    price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
    passportRequired VARCHAR(7) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
    CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),

    CONSTRAINT packagePK
        PRIMARY KEY (packageCode)
)

CREATE TABLE booking    /*Still need to do the Customer and Package delete*/
(
    customerID VARCHAR(6),
    bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
    amountPaid MONEY,
    CONSTRAINT amountPaidDefault DEFAULT 0.00,

    CONSTRAINT bookingPK
        PRIMARY KEY (customerID)
)

INSERT INTO customer
(customerID, lastname, firstname, phone, category)
VALUES
(1, 'Douglas', 'Bryan', 1478523690, 'B'),
(2, 'Picard', 'Corey', 1234657890, 'B'),
(3, 'Bond', 'Devon', 0987654321, 'B')


INSERT INTO package
(packageCode, destination, price, passportRequired)
VALUES
('YFK001', 'Orlando', 1000.47, 'Y'),
('YFK002', 'Toronto', 1000.47, 'N')

INSERT INTO booking
(customerID, bookingDate, amountPaid)
VALUES
(2, '01-07-2014', 1000.51)

执行运行并返回以下错误。 Msg 142,Level 15,State 2,Line 0

  

“TABLE”约束定义的语法不正确。

如果有人可以帮助我,那就太棒了。

谢谢, 布赖恩

2 个答案:

答案 0 :(得分:2)

问题在于预订表。默认必须使用此语法。 CONSTRAINT 是一个可选关键字,用于指示PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, or CHECK constraint定义的开始(来源MSDN

CREATE TABLE booking   
(
    customerID VARCHAR(6),
    bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
    amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
    CONSTRAINT bookingPK
        PRIMARY KEY (customerID)
)

答案 1 :(得分:1)

您的预订表有问题。检查下面更正的脚本。声明 amountPaid MONEY 之后有一个逗号,这不是必需的。因为我们不使用带有列约束的commma。

检查正确的脚本。这是成功顺利完成的。

CREATE TABLE booking    /*Still need to do the Customer and Package delete*/
(
    customerID VARCHAR(6),
    bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
    amountPaid MONEY
    CONSTRAINT amountPaidDefault DEFAULT 0.00,

    CONSTRAINT bookingPK
        PRIMARY KEY (customerID)
)