我有一个名为#My_Temp_Table的临时表,该表在MS SQL Server的200多个列中包含1和0,我需要对各列的值求和。对于SUM(),我不想单独写出每个列的名称,因此我正在寻找一种遍历列名称的方法。要获取我的临时表的所有列名,我需要以下代码:
SELECT col_names
FROM Tempdb.Sys.Columns
WHERE Object_ID = Object_ID('tempdb..#My_Temp_Table')
然后,我基本上想做这样的事情:
SELECT SUM(SELECT col_names
FROM Tempdb.Sys.Columns
WHERE Object_ID = Object_ID('tempdb..#My_Temp_Table'))
FROM #My_Temp_Table
答案 0 :(得分:0)
我为您整理了以下内容。
if exists(select name from Tempdb.Sys.Columns where Object_ID = Object_ID('tempdb..#My_Temp_Table'))
drop table #My_Temp_Table
go
if exists(select name from Tempdb.Sys.Columns where Object_ID = Object_ID('tempdb..#Temp_Table2'))
drop table #Temp_Table2
go
create table #My_Temp_Table
( column1 float
, column2 float
, column3 float
, column4 float
, column5 float )
insert into #My_Temp_Table
( column1
, column2
, column3
, column4
, column5 )
values
(1,0,3,5,3)
, (2,2,0,5,5)
, (0,7,0,3,0)
create table #Temp_Table2
( [column] varchar(100) ,results float )
declare @loop int
, @sqlCommand varchar(max)
, @columnname varchar(100)
, @result1 float = 0
, @result2 float = 0
declare @ColumnTable table (id int identity primary key, columnname varchar(100))
insert into @ColumnTable (columnname)
select name
from Tempdb.Sys.Columns
where Object_ID = Object_ID('tempdb..#My_Temp_Table')
begin
select @Loop = min(id) FROM @ColumnTable
while @Loop IS NOT NULL
begin
select @columnname = (select columnname from @ColumnTable where id = @Loop)
insert #Temp_Table2 ([column]) select @columnname
select @Loop = min(id) FROM @ColumnTable where id>@Loop
end
end
set @sqlCommand = (select top 1 stuff((select distinct ',sum('+[column] + ') '+[column] from #Temp_Table2 for xml path('')), 1, 1, '') as lookup from #Temp_Table2)
set @sqlCommand = 'select '+@sqlCommand+' from #My_Temp_Table'
exec (@sqlCommand)
这项工作可以吗?
此结果在要求的每一列中,如下所示: