【问题标题】:How to specify the type of the computed column? [duplicate]如何指定计算列的类型? [复制]
【发布时间】:2022-11-18 08:18:23
【问题描述】:

我有一个包含 payment decimal(5, 2) 列的表,我想向表中添加一个计算列:

ALTER TABLE tbl
ADD colComputed AS (ROUND(payment , 0)) / 0.6)) PERSISTED

然而,这有效,colComputed 最终变成了numeric(12, 6)

我尝试指定 ALTER TABLE tbl ADD colComputed decimal(5, 2) AS ...,但它似乎是无效语法。如何强制计算列为decimal(5, 2)

【问题讨论】:

  • colComputed AS CAST(ROUND(payment , 0)) / 0.6)) AS decimal(5, 2)) 呢?
  • 不要忘记也指定PERSISTED NOT NULL
  • @GMB 你那里有一个多余的括号。

标签: sql sql-server sql-server-2017


【解决方案1】:

您可以在列本身的定义中cast

ALTER TABLE tbl ADD colComputed AS 
  CAST( ROUND(payment , 0) / 0.6 AS decimal(5, 2) ) PERSISTED;

Demo on DB Fiddle:

create table tbl(id int primary key, payment decimal(12, 3));
insert into tbl values (1, 11), (2, 15);

alter table tbl add colcomputed as 
  cast( round(payment , 0) / 0.6 as decimal(5, 2)) persisted;
  
select t.*, round(payment , 0) / 0.6 original_computed_value
from tbl t
id payment colComputed original_computed_value
1 11.000 18.33 18.333333
2 15.000 25.00 25.000000

【讨论】:

    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 2019-10-04
    • 2018-10-01
    • 1970-01-01
    • 2019-08-17
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多