使用FK和索引选项声明创建表

时间:2014-01-23 14:45:02

标签: sql-server tsql

MS SQL Server在WITH上提供以下错误消息,该消息位于dbo.Calendar表的索引选项之前: “单词'WITH'附近的语法不正确”。 当FK声明被禁用时,错误就会消失。

CREATE TABLE dbo.Scenario
(
  ScenarioKey           int           NOT NULL  IDENTITY(1,1),
  ScenarioName          varchar(60)   NOT NULL

  CONSTRAINT [PK-C_dbo.Scenario] PRIMARY KEY CLUSTERED (ScenarioKey)

  WITH (
        PAD_INDEX  = OFF,
        FILLFACTOR = 100,
        IGNORE_DUP_KEY = OFF,
        STATISTICS_NORECOMPUTE  = OFF,        
        ALLOW_ROW_LOCKS  = ON,
        ALLOW_PAGE_LOCKS  = ON
        )
    ON [PRIMARY]
);
GO

作品。但以下失败

CREATE TABLE dbo.Calendar
(
  ScenarioKey           int             NOT NULL,
  Bucket                smalldatetime   NOT NULL,
  BucketEnd             smalldatetime   NOT NULL,

  CONSTRAINT [PK-C_dbo.Calendar] PRIMARY KEY CLUSTERED (ScenarioKey, Bucket),

  CONSTRAINT [FK_dbo.Calendar_dbo.Scenario] FOREIGN KEY (ScenarioKey)
    REFERENCES dbo.Scenario (ScenarioKey)
    ON DELETE CASCADE
    ON UPDATE CASCADE

  WITH (
        PAD_INDEX  = OFF,
        FILLFACTOR = 100,
        IGNORE_DUP_KEY = OFF,
        STATISTICS_NORECOMPUTE  = OFF,        
        ALLOW_ROW_LOCKS  = ON,
        ALLOW_PAGE_LOCKS  = ON
        )
    ON [PRIMARY]  
);
GO

语法有什么问题?

1 个答案:

答案 0 :(得分:2)

  WITH ( PAD_INDEX = OFF, /*... */ ALLOW_PAGE_LOCKS = ON )

定义与PK约束关联的索引的选项,而不是外键。所以它需要作为PK约束定义的一部分。您试图将其作为FK定义的一部分包含在内。它应该是

CREATE TABLE dbo.Calendar
  (
     ScenarioKey INT NOT NULL,
     Bucket      SMALLDATETIME NOT NULL,
     BucketEnd   SMALLDATETIME NOT NULL,
     CONSTRAINT [PK-C_dbo.Calendar] 
                PRIMARY KEY CLUSTERED (ScenarioKey, Bucket)
      WITH ( PAD_INDEX = OFF, 
             FILLFACTOR = 100, 
             IGNORE_DUP_KEY = OFF, 
             STATISTICS_NORECOMPUTE = OFF, 
             ALLOW_ROW_LOCKS = ON, 
             ALLOW_PAGE_LOCKS = ON ),
     CONSTRAINT [FK_dbo.Calendar_dbo.Scenario] 
                FOREIGN KEY (ScenarioKey) 
     REFERENCES dbo.Scenario (ScenarioKey) ON DELETE CASCADE 
                                           ON UPDATE CASCADE
  )
ON [PRIMARY]