sql - 将列表达式的结果添加为表变量创建的新列
问题描述
我确信这真的很容易,但我想不出解决方案,似乎也找不到任何可以回答我确切问题的文档。
在将值插入表变量时,如何将字段的值设置为同一表中另一个字段的表达式的结果?
例如:
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'.
我明白为什么会出现错误,我似乎无法想出解决方案。
有什么提示吗?
解决方案
您将使用子查询:
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);
请注意,这两个示例都明确列出了要插入的列。这被认为是最佳实践。
推荐阅读
- python - 只要值为 true,Pandas Dataframe 就会将它们分组
- cassandra - Cassandra 在分区聚类列上排序
- github - Git-LFS 历史下载
- c# - 将 Xamarin Essentials (Preview) MediaPicker 转换为字节 []
- javascript - 基于给定路径在 JavaScript 中填充对象的所有节点
- javascript - 如何从反应原生的api返回JSON中的随机数据
- javascript - 如何以这种格式获取时区?美国; 东部时间 (GMT -4:00)
- javascript - 反应原生 redux-persist 切片
- python - 在 Flask-SocketIO 中查找所有连接到套接字的客户端
- python - Python statsmodels GAM:如何选择惩罚?