我需要编写一个过程,我必须对未知的列名求和.
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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
将每个子标记转换为具有多个分隔符的单列-SQLConverting Every Child Tags in to a Single Column with multiple Delimiters -SQL Server (3)(将每个子标记转换为具有多个分隔符的单列-SQ
如何从多个表创建视图?How can I create a view from more than one table?(如何从多个表创建视图?)
根据前一行内的计算值创建计算值Create calculated value based on calculated value inside previous row(根据前一行内的计算值创建计算值)
如何将表格的前两列堆叠成一列,但也仅将第三How do I stack the first two columns of a table into a single column, but also pair third column with the first column only?(如何将表格的前两列堆
递归 t-sql 查询Recursive t-sql query(递归 t-sql 查询)
将月份名称转换为日期/月份编号(问题和答案的组Convert Month Name to Date / Month Number (Combinations of Questions amp; Answers)(将月份名称转换为日期/月份编号(问题和答案的组合