Solved

Looping in SQL

Posted on 2003-10-27
18
712 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
ID: 9629846
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
ID: 9630286
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
ID: 9630314
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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 4

Expert Comment

by:Sandeepk1999
ID: 9630447
You can do something like this...

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

Author Comment

by:Jag5x5
ID: 9630455
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
ID: 9630565
0
 
LVL 15

Expert Comment

by:namasi_navaretnam
ID: 9631129

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
ID: 9631527
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
ID: 9632502
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
 
LVL 4

Accepted Solution

by:
nost2 earned 350 total points
ID: 9632963
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
ID: 9633069
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
ID: 9633166
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
ID: 9635636
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
ID: 9636412
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
ID: 9636633
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
ID: 9638002
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
ID: 9640571
"Jag, apparently, neither Shogun nor I realized this was a hierarchical query."

Glad I wasnt alone :)
0
 
LVL 5

Author Comment

by:Jag5x5
ID: 9660370
Sorry about that
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

828 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