简体   繁体   English

SQL Server在nvarchar列上创建聚簇索引,强制排序

[英]SQL Server create clustered index on nvarchar column, enforce sorting

I want have a small table with two columns [Id] [bigint] and [Name] [nvarchar](63) . 我想要一个有两列[Id] [bigint][Name] [nvarchar](63)的小表。 The column is used for tags and it will contain all tags that exist. 该列用于标签,它将包含所有存在的标签。 I want to force an alphabetical sorting by the Name column so that a given tag is found more quickly. 我想通过“名称”列强制按字母顺序排序,以便更快地找到给定标记。

Necessary points are: 必要的要点是:

  1. The Id is my primary key, I use it eg for foreign keys. Id是我的主键,例如用于外键。
  2. The Name is unique as well. 名称也是唯一的。
  3. I want to sort by Name alphabetically. 我想按名称按字母顺序排序。
  4. I need the SQL command for creating the constraints since I use scripts to create the table. 由于使用脚本创建表,因此需要SQL命令来创建约束。

I know you can sort the table by using a clustered index, but I know that the table is not necessarily in that order. 我知道您可以使用聚集索引对表进行排序,但是我知道表不一定按该顺序排序。

My query looks like this but I don't understand how to create the clustered index on Name but still keep the Id as Primary Key: 我的查询如下所示,但我不了解如何在Name上创建聚簇索引,但仍将Id保留为主键:

IF NOT EXISTS (SELECT * FROM sys.objects 
               WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') 
                 AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[Tags] 
    (
        [Id] [bigint] IDENTITY(1,1) PRIMARY KEY NOT NULL,
        [Name]  [nvarchar](63) NOT NULL,

        CONSTRAINT AK_TagName UNIQUE(Name)
    )
END

Edit: 编辑:

I decided to follow paparazzo's advice. 我决定听从狗仔队的建议。 So if you have the same problem make sure you read his answer as well. 因此,如果您遇到相同的问题,请确保您也阅读了他的答案。

You should NOT do what you want to do. 应该做你想做的事。

Let the Id identity be the clustered PK. 令Id身份为聚类PK。 It (under normal use) will not fragment. 它(在正常使用下)不会碎裂。

A table has no natural order. 表格没有自然顺序。 You have to sort by to get an order. 您必须sort by才能得到订单。 Yes data is typically presented in PK order but that is just a convenience the query optimizer may or may not use. 是的,数据通常以PK顺序显示,但这只是查询优化器可能使用或可能不使用的一种便利。

Just put a non clustered unique index on Name and sort by it in the select . 只需在Name上放置一个非聚集的唯一索引,然后在select对其进行排序。

You really need bigint? 您真的需要bigint吗? That is a massive table. 那是一张大桌子。

You can specify that the Primary Key is NONCLUSTERED when declaring it as a constraint, you can then declare the Unique Key as being the CLUSTERED index. 在将其声明为约束时,可以指定主键为NONCLUSTERED ,然后可以将唯一键声明为CLUSTERED索引。

CREATE TABLE [dbo].[Tags] (
    [Id]    [bigint] IDENTITY(1,1) NOT NULL,
    [Name]  [nvarchar](63) NOT NULL,
    CONSTRAINT PK_Tag PRIMARY KEY NONCLUSTERED (Id ASC),
    CONSTRAINT AK_TagName UNIQUE CLUSTERED (Name ASC)
);

Also specifying ASC or DESC after the Column name (within the key/index declaration) sets the index sort order. 在列名之后(在键/索引声明内)还要指定ASCDESC设置索引排序顺序。 The default is usually ascending. 默认值通常是升序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM