How do I have a FILO queue for strings element in stored procedure?

I have a while loope in my query that get a string value in each loop.  I want to store these strings in a queue and then access them when the loops ends in a reverse order, first-in-last-out.  How can I do this in SQL?  Also, can I code T-SQL in query or does it have to be a stored procedure?   Thanks.
lapuccaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BrandonGalderisiCommented:
you have to re-explain because I don't really understand what you're doing here.
0
lapuccaAuthor Commented:
In this while loop, I would like to store the dbo.ResearchInterests.Name retrived in ecah loop some where in an array or queue.  This code of course has to be inside of the while loop.  For example, I got names total back when the while loop is finished, John, Mary, Nancy, Henry.
I want to get to these names in a reverse order.  The frist one poped or retried from the arry or queue should be Henry, then Nancy, Mary and John.  
I hope this is more clear of what I want to achieve.  Thank you.
	WHILE(parentId <> NULL)--USE THE PARENTID TO TRAVERSE TO ITS PARENT NODE UNTIL REACHES ROOT NODE
	BEGIN
		@interestChildId = parentId
		SELECT dbo.ResearchInterests.Name, dbo.ResearchInterests.ParentResearchInterest_id as parentId
		from dbo.ResearchInterests
		WHERE dbo.ResearchInterests.Id = @interestChildId
	END

Open in new window

0
lapuccaAuthor Commented:
Ok, what if I just insert this into a table of one column.  What's the code like to read this column table backward to retrieve the data?
Also, how do I clear all data from this table for each time the end of my inner while loop?

Thank you.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

jfmadorCommented:
You can declare a varchar before looping and adding the value to the variable

DECLARE @name as VARCHAR(1000)
SET @Name = ''

      WHILE(parentId <> NULL)--USE THE PARENTID TO TRAVERSE TO ITS PARENT NODE UNTIL REACHES ROOT NODE
      BEGIN
            SET @interestChildId = parentId
            SELECT @Name = dbo.ResearchInterests.Name + ', ' + @Name, dbo.ResearchInterests.ParentResearchInterest_id as parentId
            from dbo.ResearchInterests
            WHERE dbo.ResearchInterests.Id = @interestChildId
      END
                     --- @name will contain your name list ordered the way you want
0
lapuccaAuthor Commented:
That's a great idea.  Now, could I trouble you for how to access each of the name?  I need to get one at a time and write it to a row in a table.  I know how to do that in C# but has forgotten in sql.  Thank you so much.
0
jfmadorCommented:
You cannot use a split function like in c# but you will be able to do it using CHARINDEX AND LEFT

DECLARE @FirstName as varchar(100)
WHILE (len(@name) > 0)
BEGIN
    if (CHARINDEX(',',@Name) > 0)
    BEGIN
        SET @FirstName = LEFT(@Name,CHARINDEX(',',@Name))
        SET @Name = SUBSTRING(@Name,CHARINDEX(',',@Name) + 2, LEN(@Name) - CHARINDEX(',',@Name) -2)   -- THERE is maybe some ajustement to do here with the +2 and minus 2 to remove the comma and the blank space, I didn't try this code
    END
    ELSE
    BEGIN
       SET @FirstName = @Name
       SET @Name = ''
   END
  --- here you have @FirstName containing the first name of @Name and @Name now have left the first name until it is empty
END

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
lapuccaAuthor Commented:
Im a bit stunned on how difficult it seems to get the name "token" out of @name.  I'm starting to wonder should I insert each of the name to a sinle column temp table?  
So, with each pass, @Name is subtracted with the left most token(name), right?
let me try this and see.  Thank you.  
0
jfmadorCommented:
Yes you are right @Name is substracted with the left most token

0
lapuccaAuthor Commented:
Thank you.
0
BrandonGalderisiCommented:
"cannot use a split function like in c#"

Yes you can.  SQL Server just doesn't provide you one.  You have to write/find one.
0
jfmadorCommented:
humm... I'm sorry Brandon but how do you write a function that will return a string array using SQL ?

maybe create a stored procedure that will return a table... but the code in this function will look like the one that I post earlier...

If you have another way i'm curious to learn something new.
0
BrandonGalderisiCommented:
Here's a little one I put together
if object_id('[dbo].[fn_DelimitedToTable]') is not null
     drop function [dbo].[fn_DelimitedToTable]
go
create function [dbo].[fn_DelimitedToTable](@DelimitedString nvarchar(max), @Delimiter nvarchar(32))
returns @Values TABLE
     (ident         int not null identity primary key clustered
     ,thePosition   int not null
     ,theValue      nvarchar(max)
     )
as
/************************************************************
*
*    Author:        Brandon Galderisi
*    Last modified: 07-Oct-2008
*    Purpose:       splits an input string (@DelimitedString) 
*                   on a delimiter (@delimiter) and outputs 
*                   a table of values.
*    
*
*************************************************************/
begin
 
insert into @Values (thePosition,theValue)
		select n, substring(@delimiter + @DelimitedString + @delimiter, n + (datalength(@delimiter)/2), charindex(@delimiter, @delimiter + @DelimitedString + @delimiter, n + datalength(@delimiter)/2) - n - datalength(@delimiter)/2) as string_value
		from	dbo.vw_Nums
		where
			n <= (datalength(@delimiter + @DelimitedString + @delimiter)/2) - (datalength(@delimiter)/2)
			and substring(@delimiter + @DelimitedString + @delimiter, n, (datalength(@delimiter)/2)) = @delimiter
 
 
 
return
end
/*
-- The purpose of vw_Nums is if the source database does not have a numbers table.  This view (vw_nums)
-- will allow the parsing of up to 4 billion+ character strings with the above function.  Whether a static
-- table or this view is used for fn_DelimitedToTable, it can only split a string as long as the source 
-- numbers table.
Requires a nunbers table or this view:
create view vw_Nums
as
with   cte0 as (select 1 as c union all select 1), 
       cte1 as (select 1 as c from cte0 a, cte0 b), 
       cte2 as (select 1 as c from cte1 a, cte1 b), 
       cte3 as (select 1 as c from cte2 a, cte2 b), 
       cte4 as (select 1 as c from cte3 a, cte3 b), 
       cte5 as (select 1 as c from cte4 a, cte4 b), 
       nums as (select row_number() over (order by c) as n from cte5)
       select n from nums 
 
 
 
Sample Usage:
select * from [dbo].[fn_DelimitedToTable]('a|%25basdf|%25c|%25d','|%25')
select theValue from [dbo].[fn_DelimitedToTable]('a','|')
select * from [dbo].[fn_DelimitedToTable]('a basdf c d',' ')
*/
GO

Open in new window

0
jfmadorCommented:
Thanks Brandon it is an interresting way to do it
I never tried to use a function in a from to get a table
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.