首页 > 解决方案 > 将列表达式的结果添加为表变量创建的新列

问题描述

我确信这真的很容易,但我想不出解决方案,似乎也找不到任何可以回答我确切问题的文档。

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

例如:

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

select *
from @tableVar

理想情况下会返回:

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'.

我明白为什么会出现错误,我似乎无法想出解决方案。

有什么提示吗?

标签: sqlsql-servertsqlsql-server-2014

解决方案


您将使用子查询:

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

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


推荐阅读