Please start any new threads on our new site at 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)
 Summing Strings in SQL...

Author  Topic 

Ask SQLTeam Question

0 Posts

Posted - 2002-05-07 : 11:05:56
Ed writes "I continue to find needs for summing strings in SQL. I am basically trying to "Flatten" one-to-manys. For example, if you have a table with 2 columns, 20 rows. Lets say the first column contains the days of the week, monday, tues etc. randomly. Lets say the second column contains names, Joe, Fred, Bill etc. What I want to be able to do is say "select sum(name) from mytable where day='Monday'" and return one row that contains the two columns, one of "monday" and one with "Joe, Fred and John" in it if those happened to be the names that correspnded to those days. I know you can't "sum" strings, but it would make my life a lot simpler. Any Ideas?"

Aged Yak Warrior

616 Posts

Posted - 2002-05-07 : 12:01:57
Have a look at this code:

It should work with slight modifications.
Go to Top of Page

A custom title

1408 Posts

Posted - 2002-05-07 : 12:06:31
Check the link rrb has done string concatenation here .

Go to Top of Page
Starting Member

1 Post

Posted - 2002-05-09 : 07:31:57

Have a look at this code:

It should work with slight modifications.

Thanks, this is nice, but I was looking for something I could use in an in-line SQL statement, like "select last_name,first_name, concatenate(select all books from pubs) where last_name <> 'Jones'" where the "concatenate" function does not exisit. The results would hoepfully look like.....
Smith Fred book1, book2, book3
Johnson Ed booka, bookb
Murphy Paul bookc, booka,book1,book3

etc. I know I can do it with a "program" or stored procedure, but in my application it needs to be much more "dynamic". In Oracle I can write functions, and use them in SQL statements. Thanks!

Go to Top of Page

Most Valuable Yak

15732 Posts

Posted - 2002-05-09 : 08:30:59
In Oracle I can write functions, and use them in SQL statements.

You can write functions in SQL Server 2000, and also use them in SQL statements. It's not a feature that's limited to Oracle. I hate to gripe (yeah, I know, you don't believe that!) but if Oracle does what you want, maybe you should just use Oracle instead and not complain about SQL Server.

This link might help too:

But it's just a variation on Rob's link that was posted earlier:

The point is, they all work in SQL Server, and they do what you want done. You could even modify them to work as functions.

Go to Top of Page

Posting Yak Master

115 Posts

Posted - 2002-05-09 : 08:56:43
you can do it for one name like this

declare @foo char(1000)
select @foo = isnull(rtrim(@foo)+',', '') + rtrim(BookName)
from Books
where name = 'Smith'
select @foo

dont know how much help that'll be


Go to Top of Page

- Advertisement -