Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 select sum(@var) from table

Author  Topic 

kasabb
Starting Member

8 Posts

Posted - 2007-04-27 : 09:25:24
I need to sum a field depending on what is passed into the sp. Is there a way to accomplish this? For example ...


create procedure [dbo].[sp_Sum]
(
@var nvarchar(50)
)
as

select sum(@var) from table

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-04-27 : 09:38:09
you have to use exec()

create procedure [dbo].[sp_Sum]
(
@var nvarchar(50)
)
as
begin
declare @sql varchar(4000)
select @sql = 'select sum(' + @var + ') from table'
exec (@sql)
end


Also see this http://www.sommarskog.se/dynamic_sql.html


KH

Go to Top of Page

kasabb
Starting Member

8 Posts

Posted - 2007-04-27 : 10:44:03
But that would make me vulnerable to sql injection. Is it possible that I add the following to make sure the value being passed in isn't something malicious?


create procedure [dbo].[sp_Sum]
(
@col nvarchar(50),
@tbl nvarchar(50)
)

as

declare @iCntCol int,
@iCntTbl int,
@sql nvarchar(300)


set @col = 'myCol'
set @tbl = 'myTbl'

select @iCntTbl = count(table_name) from
information_schema.tables where table_name = @tbl

if @iCntTbl = 1
begin
select @iCntCol = count(column_name) from
information_schema.columns where table_name = @tbl
and column_name = @col

if @iCntCol = 1
begin
select @sql = 'select sum(' + @col + ') from ' + @tbl
exec (@sql)
end
end

Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-04-27 : 10:57:39
you can also use CASE statement

select sum(case @col when 'col1' then col
when 'col2' then col2
when 'col9' then col9
end)
from table


Why do you need to pass in a variable column in the first place ?




KH

Go to Top of Page

kasabb
Starting Member

8 Posts

Posted - 2007-04-27 : 11:28:43
It is an existing sp for a page that I am reviewing to ensure it is not vulnerable to sql injection.
Go to Top of Page
   

- Advertisement -