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 2000 Forums
 SQL Server Development (2000)
 Finding sum for varchar value

Author  Topic 

sanjnep
Posting Yak Master

191 Posts

Posted - 2006-05-02 : 16:20:40
Can someone help me to find sum of varchar values?
Here is sample
create table #test (val varchar(10))
select val from #test
val
----------
a
b
c
d
------------

I need abcd if I run some thing like this
select sum(val) from #test

-------
abcd

Sanjeev shrestha

Nitu
Yak Posting Veteran

81 Posts

Posted - 2006-05-02 : 16:49:09
I am sure there are lots of different ways to do this, but this is what i came up with,


Declare @Test_sum varchar(10)
Declare @val varchar(10)

DECLARE test CURSOR FOR

select val from #test

OPEN test

FETCH test INTO @val

WHILE @@Fetch_Status = 0

BEGIN
if @Test_sum is null
Set @Test_sum = @val
else
Set @Test_sum = @Test_sum + @val
FETCH test INTO @val
END

CLOSE test

DEALLOCATE test

select @Test_sum as Test_sum



Hope this Helps.
Let me know if you find another way to do this, since i am kind of new to sql and still learning.

--Nitu
Go to Top of Page

blindman
Master Smack Fu Yak Hacker

2365 Posts

Posted - 2006-05-02 : 17:06:02
[code]declare @MyFunkyVarcharSum varchar(4000)

select @MyFunkyVarcharSum = isnull(@MyFunkyVarcharsum, '') + Val
from #test
order by val

select @MyFunkyVarcharSum[/code]
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-05-03 : 02:25:31
>>select sum(val) from #test

That wont be sum but concatenation

>>Let me know if you find another way to do this, since i am kind of new to sql and still learning.

Dont use Cursor. Use blindman's approach
For concatenating values based on other columns, refer this
http://sqljunkies.com/WebLog/amachanic/archive/2004/11/10/5065.aspx?Pending=true

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -