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
 Transact-SQL (2000)
 Concatenation Function

Author  Topic 

scelamko
Constraint Violating Yak Guru

309 Posts

Posted - 2007-12-18 : 14:29:24
Guys,

I have following scenario for which I need to build a concatenating functions

ID TYPE NAME
____________________
1 D SMITH
1 D DOE
1 P RICH
1 P GARMIN
2 D JEN
2 D DORTHY

I want to create a function for which I pass ID, placeholder, type; it should give me a concatenated names.

when I execute dbo.getname(1, '|', 'D') I should get output as 1, SMITH|DOE

dbo.getname(2, '|', 'D') I should get output as 2, JEN|DORTHY.

Is there any way to accomplish this?

Thanks

dinakar
Master Smack Fu Yak Hacker

2507 Posts

Posted - 2007-12-18 : 14:31:13
Search these forums for concatenation and you will find plenty of scripts..

Dinakar Nethi
************************
Life is short. Enjoy it.
************************
http://weblogs.sqlteam.com/dinakar/
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2007-12-18 : 15:10:11
Here ya go - one way anyway:

create table t (ID int, TYPE char(1), NAME varchar(20))
insert t
select 1, 'D', 'SMITH' union all
select 1, 'D', 'DOE' union all
select 1, 'P', 'RICH' union all
select 1, 'P', 'GARMIN' union all
select 2, 'D', 'JEN' union all
select 2, 'D', 'DORTHY'

go
create function dbo.getname(@id int, @delim varchar(5), @type char(1))
returns varchar(8000)
as
begin
declare @out varchar(8000)

select @out = coalesce(@out + @delim + name, convert(varchar, @id) + ', ' + name)
from t
where id = @id
and type = @type

return @out
end

go

select dbo.getname(1, '|', 'D')
select dbo.getname(2, '|', 'D')

drop function dbo.getname
drop table t


OUTPUT:
------------------------
1, SMITH|DOE

-----------------------
2, JEN|DORTHY


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -