Reputation: 609
Say I have a table called:
TableA
The following columns exist in the table are:
Column1, Column2, Column3
what I am trying to accomplish is to see how many records are not null.
to do this I have the following case statement:
sum(Case when Column1 is not null then 1 else 0 end)
What I want is the above case statement for every table that exists from a list provided and to be run for each columns that exists in the table.
So for the above example the case statment will run for Column1, Column2 and Column3 as there are 3 columns in that particular table etc
But I want to specfiy a list of tables to loop through executing the logic above
Upvotes: 2
Views: 13351
Reputation: 44991
create procedure tab_cols (@tab nvarchar(255))
as
begin
declare @col_count nvarchar(max) = ''
,@col nvarchar(max) = ''
select @col_count += case ORDINAL_POSITION when 1 then '' else ',' end + 'count(' + QUOTENAME(COLUMN_NAME,']') + ') as ' + QUOTENAME(COLUMN_NAME,']')
,@col += case ORDINAL_POSITION when 1 then '' else ',' end + QUOTENAME(COLUMN_NAME,']')
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = @tab
order by ORDINAL_POSITION
declare @stmt nvarchar(max) = 'select * from (select ' + @col_count + ' from ' + @tab + ') t unpivot (val for col in (' + @col + ')) u'
exec sp_executesql @stmt
end
Upvotes: 3
Reputation: 67331
Wouldn't it be easy as this?
SELECT AccountID
,SUM(Total) AS SumTotal
,SUM(Profit) AS SumProfit
,SUM(Loss) AS SumLoss
FROM tblAccount
GROUP BY AccountID
If I understand this correctly you want to get the sums, but not for all rows in one go but for each accountID separately. This is what GROUP BY
is for...
If ever possible try to avoid loops, cursors and other procedural approaches...
With different tables you will - probably - need exactly the statement I show above, but you'll have to generate it dynamically and use EXEC
to execute it. You can go through INFORMATION_SCHEMA.COLUMNS
to get the columns names...
But:
data_type like 'decimal%'
or similar...GROUP BY
?To be honest: I think, there is no real-generic-one-for-all approach for this...
Upvotes: 0