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

Can I create an index on a computed column?

我的table有这个结构。

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

我想要做的是添加一个名为 Ascii 的列,其定义为 (ASCII([WordId]))

有没有办法可以添加它,然后在此列 + WordId + CategoryId 上创建索引?我也可以这样做并让它根据我已有的数据自动更新吗?

您可以通过使计算列 persisted

来自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. Marking a computed column as PERSISTED lets you create an index on a computed column that is deterministic

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] ),
);

要更改 table 添加计算列,请使用此

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