Monday, March 12, 2012

PLS HELP:Merge cells - use cursor?

Hi,
I just wonder if someone could help me here:
Say, i have a table with one column: 'Name'
Name1
Name2
Name3
...
I need to get the string of "Name1, Name2, Name3, ..."
The only way i see is to use cursor - but i know cursors aren't the best way
if an alternative exists...
So is there a way to just use a select to perform that?
Thank you,
AndreyYes, I think you'll need to visit each row.
However instead of using a cursor, try using a table variable (excuse any
typos)
declare @.OutputList varchar(8000)
set @.OutputList=''
declare @.Rows integer
declare @.Val varchar(255)
declare @.I integer
declare @.T1 table (RowNum integer identity(1,1) primary key, RowData
varchar(255))
insert @.T1 select name from YourTable
set @.Rows = @.@.ROWCOUNT
if @.Rows<>0
begin
set @.I=0
while @.I<@.Rows
begin
set @.I=@.I+1
select @.Val=@.T1.RowData where @.T1.RowNum = @.I
set @.OutputList = @.OutputList + @.Val + ','
end
set @.OutputList = left(@.OutputList,Len(@.OutputList)-1) -- get rid of final
comma
end
....gtr
"MuZZy" wrote:

> Hi,
> I just wonder if someone could help me here:
> Say, i have a table with one column: 'Name'
> Name1
> Name2
> Name3
> ...
> I need to get the string of "Name1, Name2, Name3, ..."
> The only way i see is to use cursor - but i know cursors aren't the best w
ay if an alternative exists...
> So is there a way to just use a select to perform that?
> Thank you,
> Andrey
>|||Isn't that just a matter of formatting the output for display? So do it
in the client app, which is where presentation belongs and where it's
generally easier to do this kind of thing.
Otherwise, maybe something like this will help:
CREATE TABLE Foo (name VARCHAR(10) PRIMARY KEY)
SELECT
MAX(CASE ord WHEN 1 THEN name END)+
MAX(CASE ord WHEN 2 THEN ','+name ELSE '' END)+
MAX(CASE ord WHEN 3 THEN ','+name ELSE '' END)+
MAX(CASE ord WHEN 4 THEN ','+name ELSE '' END)+
MAX(CASE ord WHEN 5 THEN ','+name ELSE '' END)
/* repeat as required... */
FROM
(SELECT P.name, COUNT(*)
FROM Foo AS P,Foo AS Q
WHERE P.name >= Q.name
GROUP BY P.name) AS T(name,ord)
David Portas
SQL Server MVP
--

No comments:

Post a Comment