在 table 变量创建中将列表达式的结果添加为新列

Adding result of column expression as new column on table variable creation

我确信这真的很简单,但我想不出解决方案,而且似乎找不到任何文档来回答我的确切问题。

在将值插入 table 变量时,如何将字段的值设置为同一 table 中另一个字段的表达式的结果?

例如:

declare @tableVar table(
    [col1] int,
    [col2] dec(18,2),
    [col3] dec(18,2)
)
insert into @tableVar
values (100,.03,[col1] * [col2])

select *
from @tableVar

理想情况下 return:

col1 col2 col3
100  0.03 3.00

但是我得到了这个错误:

Msg 207, Level 16, State 1, Line 19
Invalid column name 'col1'.

Msg 207, Level 16, State 1, Line 19
Invalid column name 'col2'.

我明白为什么我会收到错误消息,但我似乎想不出解决方案。

有什么提示吗?

您将使用子查询:

insert into @tableVar (col1, col2, col3)
    select col1, col2, col1 * col2
    from (values (100, 0.03)) v(col1, col2);

或者,更好的是,使用计算列:

declare @tableVar table (
    col1 int,
    col2 dec(18, 2),
    col3 as ( convert(dec(18, 2), col1 * col2) )
);

insert into @tableVar (col1, col2)
    values (100, 0.03);

请注意,这两个示例都明确列出了要插入的列。这被认为是最佳实践。

您需要 values 构造 :

insert into @tableVar (col1, col2, col3)
   select col1, col2, col1 * col2
   from (values (100, .03) 
        ) t(col1, col2);