TSQL Passing a varchar variable of column name to SUM function(TSQL将列名的varchar变量传递给SUM函数)
问题描述
我需要编写一个过程,我必须对未知的列名求和.
I need to write a procedure where I have to sum an unknown column name.
我可以访问的唯一信息是列位置.
The only information I have access to is the column position.
我可以使用以下方法获取列名:
I am able to get the column name using the following:
SELECT @colName = (SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TABLENAME' AND ORDINAL_POSITION=@colNum)
然后我有以下内容:
SELECT @sum = (SELECT SUM(@colName) FROM TABLENAME)
然后我收到以下错误:
操作数数据类型 varchar 对求和运算符无效
我对如何使这项工作感到困惑.我看过很多关于转换和转换的帖子,但我不能转换为浮点数、数字等,因为这是一个名字.
I am confused about how to make this work. I have seen many posts on convert and cast, but I cannot cast to an float, numeric, etc because this is a name.
我将不胜感激.
谢谢
推荐答案
这是不可能的.您必须组装 SQL 查询,然后执行它.像这样:
This is not possible. You will have to assemble the SQL query and then execute it. Something like this:
SET @sqlquery = 'SELECT SUM(' + @colName + ') FROM TABLENAME'
EXECUTE ( @sqlquery )
相应调整.
这篇关于TSQL将列名的varchar变量传递给SUM函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TSQL将列名的varchar变量传递给SUM函数


- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01