【问题标题】:What is "ON" in the end of the query?查询末尾的“ON”是什么?
【发布时间】:2020-10-30 02:45:11
【问题描述】:

我的查询看起来像这样:

...
GO
CREATE TABLE [schema_name].[table_name] (
    [field1] [int] not null,
    [field2] [int] not null,
CONSTRAINT [PK_Some_name] PRIMARY KEY CLUSTERED ([field1] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CommonData]
) ON [CommonData]
GO
...

问题是什么是“ON [CommonData]”?为什么会出现两次?这部分的意义何在?[CommonData] 是什么?这类似于默认功能还是自定义功能?

【问题讨论】:

  • T-SQL 文档会回答这个问题。提示:they specify file groups,分别用于约束和表。
  • 您可能只需要一个ON 作为集群主键 表。我认为所有三个排列(在表上指定、聚集索引或两者都指定)将导致相同的最终结果
  • @MartinSmith 仅当您对主(默认)文件组做出假设时,这才是正确的。
  • @SM 或者不是。我刚刚测试过了。我创建了一个名为 CommonData 的文件组 - 这是 not 默认值,在这种情况下,在任一位置指定都会产生相同的最终结果

标签: sql-server tsql ddl


【解决方案1】:

ON [CommonData] 定义了用于物理存储数据的file group

您在问题中使用的语法为聚集索引和表定义了它。不过,它们实际上并不是两个独立的实体。聚集索引表。

您可以省略其中任何一个,最终得到相同的结果。该表被创建为文件组 CommonData 上的聚集索引,并且如果未明确指定,则在该文件组上创建该表上的任何非聚集索引。

即下面的两次尝试都返回相同的结果

+--------------+------------+
|     name     |    name    |
+--------------+------------+
| PK_Some_name | CommonData |
| ix_field3    | CommonData |
| ix_field2    | CommonData |
+--------------+------------+

drop TABLE if exists dbo.table_name

go

CREATE TABLE dbo.[table_name] (
    [field1] [int] not null,
    [field2] [int] not null,
    [field3] [int] not null INDEX ix_field3,  /*Not specifying filegroup*/
CONSTRAINT [PK_Some_name] PRIMARY KEY CLUSTERED ([field1] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON CommonData

CREATE INDEX ix_field2 ON  dbo.[table_name]([field2]) /*Not specifying filegroup*/

SELECT i.name, ds.name
FROM sys.indexes i
JOIN sys.data_spaces ds on ds.data_space_id = i.data_space_id
WHERE object_id = object_id('dbo.table_name')

GO

drop TABLE if exists dbo.table_name

go

CREATE TABLE dbo.[table_name] (
    [field1] [int] not null,
    [field2] [int] not null,
    [field3] [int] not null INDEX ix_field3,  /*Not specifying filegroup*/
CONSTRAINT [PK_Some_name] PRIMARY KEY CLUSTERED ([field1] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)  ON CommonData
)

CREATE INDEX ix_field2 ON  dbo.[table_name]([field2]) /*Not specifying filegroup*/

SELECT i.name, ds.name
FROM sys.indexes i
JOIN sys.data_spaces ds on ds.data_space_id = i.data_space_id
where object_id = object_id('dbo.table_name')

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多