Solved

Looping in SQL

Posted on 2003-10-27
18
708 Views
Last Modified: 2007-12-19
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.
0
Comment
Question by:Jag5x5
  • 6
  • 3
  • 2
  • +7
18 Comments
 
LVL 13

Expert Comment

by:MikeWalsh
Comment Utility
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?
0
 
LVL 1

Expert Comment

by:nguyenn
Comment Utility
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

0
 
LVL 5

Author Comment

by:Jag5x5
Comment Utility
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?
0
 
LVL 4

Expert Comment

by:Sandeepk1999
Comment Utility
You can do something like this...

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

Author Comment

by:Jag5x5
Comment Utility
Only problem with that is it is VB context and won't work in SQL.  I need the SQL looping.
0
 
LVL 3

Expert Comment

by:galori
Comment Utility
0
 
LVL 15

Expert Comment

by:namasi_navaretnam
Comment Utility

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
0
 
LVL 9

Expert Comment

by:PaulBarbin
Comment Utility
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
0
 
LVL 18

Expert Comment

by:ShogunWade
Comment Utility
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".
0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 4

Accepted Solution

by:
nost2 earned 350 total points
Comment Utility
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
0
 
LVL 26

Expert Comment

by:Hilaire
Comment Utility
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
0
 
LVL 18

Expert Comment

by:ShogunWade
Comment Utility
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


?

0
 
LVL 5

Author Comment

by:Jag5x5
Comment Utility
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
0
 
LVL 9

Expert Comment

by:PaulBarbin
Comment Utility
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
0
 
LVL 5

Author Comment

by:Jag5x5
Comment Utility
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
0
 
LVL 5

Author Comment

by:Jag5x5
Comment Utility
Although I solved this myself it was reading nost2's answer that insired me to do it so I awarded the points to him.
0
 
LVL 18

Expert Comment

by:ShogunWade
Comment Utility
"Jag, apparently, neither Shogun nor I realized this was a hierarchical query."

Glad I wasnt alone :)
0
 
LVL 5

Author Comment

by:Jag5x5
Comment Utility
Sorry about that
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

I wrote this interesting script that really help me find jobs or procedures when working in a huge environment. I could I have written it as a Procedure but then I would have to have it on each machine or have a link to a server-related search that …
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now