简体   繁体   English

我可以在计算列上创建索引吗?

[英]Can I create an index on a computed column?

My table has this structure. 我的桌子有这种结构。

CREATE TABLE [dbo].[Word] (
    [WordId]       VARCHAR (20) NOT NULL,
    [CategoryId]   INT          DEFAULT ((1)) NOT NULL,
    PRIMARY KEY CLUSTERED ([WordId] ASC),
);

What I would like to do is to add a column called Ascii with a definition as (ASCII([WordId])) 我想要做的是添加一个名为Ascii的列,其定义为(ASCII([WordId]))

Is there a way that I can add this and then create an index on this column + WordId + CategoryId ? 有没有办法我可以添加这个,然后在此列+ WordId + CategoryId上创建索引? Also can I do this and have it automatically updated based on the data I already have existing? 我也可以这样做,并根据我已经存在的数据自动更新吗?

You can do that by making the computed column persisted 您可以通过使计算列persisted

From MSDN 来自MSDN

Specifies that the SQL Server Database Engine will physically store the computed values in the table, and update the values when any other columns on which the computed column depends are updated. 指定SQL Server数据库引擎将物理存储表中的计算值,并在更新计算列所依赖的任何其他列时更新值。 Marking a computed column as PERSISTED lets you create an index on a computed column that is deterministic 将计算列标记为PERSISTED可以在计算列上创建一个确定性的索引

CREATE TABLE [dbo].[Word] 
(
    [WordId]       VARCHAR (20) NOT NULL,
    [CategoryId]   INT          DEFAULT ((1)) NOT NULL,
    [Ascii]        as (ASCII([WordId])) persisted,
    PRIMARY KEY CLUSTERED ([WordId] ,[CategoryId],[Ascii] ),
);

To alter the table with addition of computed column use this 要通过添加计算列来更改表,请使用此选项

ALTER TABLE [dbo].[Word] ADD [Ascii] AS (ASCII([WordId])) persisted;

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

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