2
SELECT 
    name 
FROM 
    sys.all.column 
WHERE object_id = (SELECT object_id 
                   FROM sys.all_objects 
                   WHERE name ='name of my table' and type = 'TT') 
  AND name NOT IN (list of columns that I don't need)

How do I sum all the values of the returned columns from the preceding SQL query?

23
  • what do you mean by sum all the values of the returned columns? By the looks of it, name is probably a text column. Sum of what? Commented Dec 31, 2016 at 18:56
  • The code will return all the columns in tye specified table. I want to sum the value of each column of a particular row Commented Dec 31, 2016 at 18:59
  • so you want to sum column the values of a single row? Why can't you just write the column names -- how many columns do you have? Commented Dec 31, 2016 at 19:01
  • 2
    in what crazy model do you columns change? Commented Dec 31, 2016 at 19:04
  • 1
    yes this is my point. This is not a nosql system, this is a relational system your columns should not be added at run time. This is an indication of a bad design or a poor tool choice. Commented Dec 31, 2016 at 19:07

3 Answers 3

2

Another option which does not require dynamic SQL, but only a CROSS APPLY or two

Just for fun, I add Min, Max, and Avg just to illustrate... Also added a PctOfTotal or Common-Size

Declare @YourTable table (ID int,CustName varchar(50),Sales_Jan int,Sales_Feb int,Sales_Mar int)
Insert into @YourTable values
(1,'John Smith',25,25,50),
(2,'Jane Doe'  ,35,20,null)

Select A.*
      ,C.*
      ,PctOfTotal = Format(C.Total*1.0/Sum(C.Total) over (),'0.00%')
 From  @YourTable A
 Cross Apply (Select XMLData=cast((Select A.* For XML RAW) as xml)) B
 Cross Apply (
                Select Total = Sum(Value)
                      ,Min   = Min(Value)
                      ,Max   = Max(Value)
                      ,Avg   = Avg(Value)
                 From  (
                        Select Value  = attr.value('.','int') 
                         From  B.XMLData.nodes('/row') as A(r)
                         Cross Apply A.r.nodes('./@*') AS B(attr)
                         Where attr.value('local-name(.)','varchar(100)') Like 'Sales_%'
                         --Or you can Exclude Specific Columns
                         --Where attr.value('local-name(.)','varchar(100)') not in ('ID','CustName')
                       ) S
             ) C

Returns

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

exactly as I was saying -- use xml. very cute answer. Does it get slow where there are a lot of columns.... this guy is adding 12 a year.
@Hogan I'm assuming "cute answer" is a compliment and not just mocking me :) Performance is respectable. Just ran a test on 6,681 records with 24 columns to add (yield curve rates). Results returned in 0.634 seconds (while streaming NetFlix)
yes cute answer was a compliment -- this technique is def. going in my bag of tricks. (transport speed has little effect on performance would be my guess -- so who cares about NetFlix?) I'll try it on a couple million rows when I get in on Tuesday and let you know.
@Hogan Please do, but I can't this would be my approach on a millions of rows.. odds are I would re-think the structure. The 6,681 records was the only table I had that fit his model. Hopefully, this will buy him a little time to change his structure,
@Hogan In all honesty, the word cute made me smile. It was unexpected from someone of your ranking/reputation... Yeah, we watch and follow..
1

If I understand correctly, you want to find out some columns from meta tables that you want to sum, and then sum those columns on the given table. You can use dynamic SQL to achieve this:

create table t(a integer, b integer, c integer);

insert into t values(1,2,3);

declare @tab varchar(100);
declare @sql varchar(max);
set @sql = '';
set @tab = 't';

select @sql = @sql + '+' + a.name from sys.all_columns a
inner join 
sys.all_objects b
on a.object_id = b.object_id
where b.name = @tab
and a.name not in ('c');

set @sql = 'select ' + stuff(@sql, 1, 1, '') + ' from ' + @tab;

exec(@sql);

Produces:

3

5 Comments

@Hogan and a.name not in ('c'); to give example of how to ignore a column
@GurwinderSingh Just remember this answer the next time you mock my dynamic pivots. :) --- Happy New Year!
@JohnCappelleti Hey.. Happy new year. I tried a bit and it worked but obviously no match for yours. :)
@John I admire your queries. I am sorry if you felt that I was mocking them.
@GurwinderSingh Honestly, never thought that for a second. 1) I'm pretty thick skinned. 2) I have a GREAT sense of humor and 3) If you want to mock me, you'd better up your game... my wife was going to turn pro.
0
select col1,col2,col3,col4,NVL(col1,0)+NVL(col2,0)+NVL(col3,0)+NVL(col4,0)
from
(select *
from sys.all.column
where object_id =(select object_id from sys.all.object where name ='name of my table') 
  and name not in (list of columns that I dont need).)


   A  |  B   |  Total(col1+col2)
------+------+-------
   1  |  2   |   3
---------------------
   1  |      |   1

Whatever columns you get, sum it and put them as seperate column in the result table.

5 Comments

This answer is very wrong. Please test and see why.
I'm not sure what you are doing here.
@Hogan.: what ver be the result then just get the summed value from the columns.
why do you think sys.all.column (which does not exist btw) would have a column named "col1"? (or "col2" etc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.