一条记录所有字段如何相加
有一张表,表里面的字段不固定,可以添加删除。字段类型是smallmoney。
现在想把一条记录的所有列相加。SQL语句如何实现
[解决办法]
create table Test (id varchar(10),Col0 int,Col1 int,Col2 int,Col3 int,Col4 int,Col5 int,Col6 int,Col7 int,Col8 int,Col9 int,Col10 int,Col11 int,Col12 int,Col13 int,Col14 int,Col15 int,Col16 int,Col17 int,Col18 int,Col19 int)insert test values(1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19)insert test values(2,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39)insert test values(3,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119)insert test values(4,200,201,202,203,204,205,206,207,208,209,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019)insert test values(5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)godeclare @sql varchar(8000)set @sql = 'select t.* , 'select @sql=isnull(@sql + '' , '') + name + '+'from syscolumns where id=object_id('test') and name != 'ID'select @sql=left(@sql,len(@sql)-1) + ' [所有列相加的和] from test t' exec(@sql)/*id Col0 Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10 Col11 Col12 Col13 Col14 Col15 Col16 Col17 Col18 Col19 所有列相加的和 ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 1902 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 5903 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 21904 200 201 202 203 204 205 206 207 208 209 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 221905 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0*/drop table test