【问题标题】:Index on computed column of `int` type can't be created, because of column is imprecise无法在“int”类型的计算列上创建索引,因为列不精确
【发布时间】:2013-07-16 10:20:04
【问题描述】:

假设有一个表,比如:

create table #data
(
    ID int identity(1, 1),
    Value float,
    VCluster as (ID % 5),
    VType as (cast(case when Value > 1 then 1 when Value < -1 then -1 else 0 end as int))
)

我需要在其计算列上创建两个索引,如下所示:

create index #ix_data_1 on #data (VCluster)
create index #ix_data_2 on #data (VType)

第一个创建良好,但是当我尝试创建第二个时,我收到错误消息:“无法在表 '#data' 上创建索引或统计信息 '#ix_data_2',因为计算列 'VType ' 是不精确的,没有持久化..."

我查询系统视图为:

select c.name, c.system_type_id, t.name as type_name
from tempdb.sys.columns c
    join tempdb.sys.types t on t.system_type_id = c.system_type_id
where c.object_id = object_id('tempdb..#data')
order by c.column_id

得到以下结果:

name       system_type_id type_name
---------- -------------- ----------
ID         56             int
Value      62             float
VCluster   56             int
VType      56             int

所以,VType 列的类型是 int,但它似乎不知何故“不是很 int”。 我知道我可以创建列 persisted 并创建索引,但是有没有办法避免它并使列 VType "100% int"?

【问题讨论】:

  • @Damien_The_Unbeliever:你为什么不写这个作为答案呢?没错。

标签: sql-server indexing type-conversion calculated-columns


【解决方案1】:

导致它不精确的不是结果类型——而是它对float 输入值的依赖。除了您已经排除的解决方案之外,您无能为力 - 将其标记为 PERSISTED

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2023-03-19
    • 2019-03-09
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多