Looping in SQL

Jag5x5
Jag5x5 used Ask the Experts™
on
I need to loop in a Stored Proc so I can recursively decide which records A user can see.  Wondering how best to do this.  In VB I would use a do..loop statement until the qdf.results = 0 indicating that there were no appended records.  wondering how to do this solely on the sql server.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
well there are a couple different ways to loop in sql. I am not a VB guy so I don't know the qdf.results. Can you give me a better picture of what you are trying to do?

Commented:
You can use cursor:

declare @Var1 varchar(10)
declare @Var2 varchar(10)
declare YourCursor cursor for
Select Field1, Field2 From YourTable

fetch next from YourCurstor into @Var1, @Var2


while @@fetch_status = 0  --indicate there are still records
begin
      --Your code here
      fetch next from YOurCursor into @Var1, @Var2      
end

close YourCursor
deallocate YourCursor

Author

Commented:
Actually I am trying to loop through a table and insert the ID's into a table so that I can later select those ID's to display in a result set.

flxID|lnm|fnm|Supid
1|blow|joe|1
2|blow|jane|1
3|smith|john|16
4|smith|jane|3
5|doe|john|2
6|doe|jane|2

if this is the data set then I want to have a table with (Asuming Joe Blow is logged in)

id
1
2
5
6

IF Jane Blow was logged in it would just be
id
5
6

So then I can report on everyone who reports to the person who is logged in.

Make sense?
Should you be charging more for IT Services?

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

You can do something like this...

While qdf.results <> 0
Begin
      If (SomeCondition)
            Break
      Else
            Continue
End

Author

Commented:
Only problem with that is it is VB context and won't work in SQL.  I need the SQL looping.

At the begining of SP:
create table #temp
(
   col1  int
)

Inside Cursor Loop:
insert into #temp (col1) values (@val1)


Outside the loop:

select col1
from #temp

HTH
You've gotten some good help on how to cycle through rows in SQL Server.  

However, the proper solution to the problem is NOT to use recursion (cursors) when you don't have to.
This is a classic problem that developers from other languages (other than sql) have.  Since recursion is the only way to accomplish this in many languages, developers often aren't prepared to use sql to its fullest.  That is, use set based operations.  This is the real power of sql.

You can just pass the stored procedure the id of the supervisor and have the stored procedure either produce a rowset for VB or you could actually insert it into a table if you like.

select flxID from myTable where Supid = @supid

Paul
I think the fundamental problem here is that your are thinking itteratively (not recursively) which is a 3GL thing as paul says.

When developing in SQL you must get into the mindset of "Set Theory".
Commented:
What we have here is a hierarchical query, there is no simple way to solve that using sql and set theory. Here is a stored procedure that can be used:

create procedure p2 (@parent int) as
declare @level int
select @level = 1
create table #stack(parent int,child int,level int)
insert into #stack select supid,flxid,0 from superv
where supid = @parent and flxid = supid
insert into #stack select supid,flxid,1 from superv
where supid = @parent and flxid <> supid
while @@rowcount > 0
begin
select @level = @level + 1
insert into #stack
select supid,flxid,@level
from superv where supid in (select child from #stack where level = @level - 1)
end
select child from #stack

Commented:
Hi,
YES You can do this with standard SQL without using cursors.
I just have to know the maximum number of levels in your hierarchy

This query works with up to 4 hierarchic levels

select distinct coalesce(a.flxID, b.flxID, c.flxID, d.flxID)
from employee a right outer join employee b on a.supID = b.flxID
right outer join employee c on b.supID = c.flxID
right outer join employee d on c.supID = d.flxID
where d.flxID=@parentID

but you can build a query that supports more levels based on this model (eg up to 5 levels in the query below)

select distinct coalesce(a.flxID, b.flxID, c.flxID, d.flxID, e.flxID)
from employee a right outer join employee b on a.supID = b.flxID
right outer join employee c on b.supID = c.flxID
right outer join employee d on c.supID = d.flxID
right outer join employee e on d.supID = e.flxID
where e.flxID=@parentID

you can use this select in an insert-select statement, or use it as a sub-select in a more complex statement, without building a temporary table
eg
select lnm, fnm, emailadress from employee where flxID in (sub-select)

HTH

Hilaire
Im confused....   Is this the question ....

Actually I am trying to loop through a table and insert the ID's into a table so that I can later select those ID's to display in a result set.

flxID|lnm|fnm|Supid
1|blow|joe|1
2|blow|jane|1
3|smith|john|16
4|smith|jane|3
5|doe|john|2
6|doe|jane|2


etc......


isnt the answer simply....


SELECT flxid FROM Table1 WHERE supid=@supid


?

Author

Commented:
ShogunWade NO actually if you read the entire question it says if Joe is logged in I want to see id 1,2,5,6 because Jane (id 2) reports to Joe(ID 1) and John(id 5) reports to Jane etc..

I don't know the maximum levels and if I did I could do it more simply by looping that number of times.  The issue is I just need to know when I run a subquery in SQL how can I tell the number of return rows??

All this talk of Set Theory and Cursurs is good but this should be simplistic.  I have tried all of these answers and none of them work.. I am just trying to find out how to tell how many new records I added to a table..

I currently have this working by looping 100 times but would like to make it more efficent.

Jag
Jag, apparently, neither Shogun nor I realized this was a hierarchical query.  This question has been hashed many times before.  Search this site for "hierarchy" or "tree".  Check out posts by Nigel, and this link:

http://www.4guysfromrolla.com/webtech/sqlguru/q121799-1.shtml

Paul

Author

Commented:
Actually this is how I fixed this problem and it works well.

SELECT ebflxid INTO #supervisor
FROM bpmgapps3.VHR_DATASQL.dbo.EBASE
WHERE left(ebfirstname,1) + eblastname = @ad_supname

set @intlp = 0
set @intrcnt = 0

while (select count(ebflxid) from #supervisor) <> @intrcnt
      begin
            set @intrcnt = (select count(ebflxid) from #supervisor)

            INSERT INTO #supervisor ( ebflxid )
            SELECT distinct ej1.EjFlxIDEb
            FROM (SELECT EJ.EjFlxIDEb FROM #supervisor s
                  LEFT JOIN bpmgapps3.VHR_DATASQL.dbo.EJob AS EJ
                  ON s.ebflxid = EJ.EjSupervisorFlxIDEb
                  AND EJ.EjDateBeg <=getdate()
                  AND (EJ.EjDateEnd>=getdate() Or EJ.EjDateEnd Is Null)) ej1
                  LEFT JOIN #supervisor s ON
                  ej1.EjFlxIDEb=s.ebflxid
                  

                  WHERE s.ebflxid Is Null and ej1.ejflxideb is not null

            if @intlp > 30 break
            
            set @intlp = @intlp +1

      end

Author

Commented:
Although I solved this myself it was reading nost2's answer that insired me to do it so I awarded the points to him.
"Jag, apparently, neither Shogun nor I realized this was a hierarchical query."

Glad I wasnt alone :)

Author

Commented:
Sorry about that

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial