TSQL将列名的varchar变量传递给SUM函数
- 作者: 陳先生c
- 来源: 51数据库
- 2022-12-30
问题描述
我需要编写一个过程,我必须对未知的列名求和.
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 )
相应调整.
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
