本文介紹了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函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!