Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

How to convert my cursor tsql to set based Expand / Collapse
Author
Message
Posted Wednesday, July 31, 2013 6:31 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, August 7, 2013 10:06 PM
Points: 6, Visits: 22
Hello All....

I was just thinking about a query I need to write and know how to do it with cursors but would like to try and make it happen using a set based approach. Not sure if it can be done.

Here are my requirements:

I need to group the following into a pool.
step 1 - Get all House Ids
step 2 - For each house id, get all people linked directly to that house
step 3 - for each of those people , get any additional house ids linked to them
step 4 - for each of those additional house ids, get any additional people linked to them

e.g. result
Pool 1 =
House Id | people Id
1 | 1
1 | 2
2 | 2
3 | 2
3 | 4

I hope I have made sense, I can see how easy it would be to code using cursors but an not sure of the set based approach.

Thoughts??

Cheers
Post #1479755
Posted Wednesday, July 31, 2013 8:01 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Thursday, August 28, 2014 8:30 PM
Points: 3,627, Visits: 5,273
Sounds like you have what is called an adjacency list with people/houses and you may be able to resolve this with a recursive CTE (or perhaps not).

Two questions:
1. Do you need to stop at step 4 or resolve all the way through to the end?
2. What happens when the same house ID comes up for more than one person? In other words, do you need to ignore duplications on each additional resolution step?

If the answer is Yes to ignoring duplicates, you may need to do this with a set-based loop.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1479768
Posted Wednesday, July 31, 2013 8:21 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, August 7, 2013 10:06 PM
Points: 6, Visits: 22
Thanks for your response...

I suppose technically I could continue all the way to the end but at this stage I want to stop at step 4 (which should be the end anyway)

And yes, I do not want duplicates, so the House | Person combination is unique, but as with my example, a house with multiple persons is perfectly valid.

Do you have some example TSql I could look at/play with?

Cheers
Post #1479769
Posted Wednesday, July 31, 2013 8:35 PM
SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Sunday, September 29, 2013 1:24 AM
Points: 429, Visits: 1,721
If you could give us some sample data in table form it would be a lot easier to help you.

I could be totally off-base, but my first thought is to use multiple CTEs. I'm not sure that recursion is even necessary. Without the tables or data this is just pseduo-code so run with it.


WITH
cteHouses AS --step 1 - Get all House Ids
(SELECT * FROM HouseTable),
cteResidents AS --step 2 - For each house id, get all people linked directly to that house
(SELECT *
FROM cteHouses h
INNER JOIN ResidentsTable r
ON h.houseID = r.HouseID),
cteHouseXref AS --step 3 - for each of those people , get any additional house ids linked to them
(SELECT *
FROM cteHouses h1
INNER JOIN ResidentsTable r1
ON h1.houseID = r1.HouseID),
cteResidentXref AS --step 4 - for each of those additional house ids, get any additional people
(SELECT *
FROM cteHouseXref h2
INNER JOIN ResidentsTable r2
ON h2.houseID = r2.HouseID)
SELECT
*
FROM
cteHouses h3
INNER JOIN
cteResidents r3
ON h3.houseID = r3.HouseID
INNER JOIN
cteHouseXref r4
ON h4.houseID = r4.HouseID
INNER JOIN
cteResidentXref r5
ON h5.houseID = r5.HouseID


 
Post #1479771
Posted Wednesday, July 31, 2013 11:03 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, August 7, 2013 10:06 PM
Points: 6, Visits: 22
Steven Willis (7/31/2013)
If you could give us some sample data in table form it would be a lot easier to help you.

I could be totally off-base, but my first thought is to use multiple CTEs. I'm not sure that recursion is even necessary. Without the tables or data this is just pseduo-code so run with it.

 


Thanks for responding but I am not quite sure I get where you are going.

The source data I have is simply a table like the following and I have created a very small bit of data:

CREATE TABLE HouseResident
(
HouseId INT,
ResidentId INT
)

INSERT INTO HouseResident
VALUES(194290,2300365)

INSERT INTO HouseResident
VALUES(194291,2300365)

INSERT INTO HouseResident
VALUES(194291,2300847)

INSERT INTO HouseResident
VALUES(192099,2300847)

INSERT INTO HouseResident
VALUES(192099,2300914)


The result set I need to insert into a table and it should look like the following:

PoolId | HouseId | ResidentId

1 | 194290 | 2300365
1 | 194291 | 2300365
1 | 194291 | 2300874
1 | 192099 | 2300874
1 | 192099 | 2300914

Basically there is a heap of data that I need to pool together like above.

Hope I have made sense?

EDIT > I have just discovered that I need to go more than 4 levels deep.
So I would need a procedure that would "continue to the end" if you get me.


Cheers
Post #1479784
Posted Thursday, August 1, 2013 4:33 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Thursday, August 28, 2014 8:30 PM
Points: 3,627, Visits: 5,273
Your sample data looks good. But the results set is simply the sample data directly SELECTed out of the table you provided.

You need to give us consumable sample data (DDL and INSERTs like you did) but also you need to tell us how that data should look after transformation.

I'm not sure I can help you much more today as I'm catching a long flight in the next few hours so will be out of pocket for about 18 hours.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1479866
Posted Thursday, August 1, 2013 7:36 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: 2 days ago @ 9:46 AM
Points: 7,224, Visits: 13,696
This works but it's quite expensive to run:

WITH Pass1 AS (
SELECT
PoolId = DENSE_RANK() OVER(ORDER BY ResidentId),
HouseId, ResidentId
FROM #HouseResident
),
Pass2 AS (
SELECT
PoolId = MIN(PoolId) OVER (PARTITION BY HouseId),
HouseId, ResidentId
FROM Pass1
),
Pass3 AS (
SELECT
PoolId = MIN(PoolId) OVER (PARTITION BY ResidentId),
HouseId, ResidentId
FROM Pass2
),
Pass4 AS (
SELECT
PoolId = MIN(PoolId) OVER (PARTITION BY HouseId),
HouseId, ResidentId
FROM Pass3
)
SELECT
PoolId = MIN(PoolId) OVER (PARTITION BY ResidentId),
HouseId,
ResidentId
FROM Pass4;

Also, you'd have to add more blocks until no changes are found, in order to "reach the end". Nesting CTE's like this can get very expensive after 3 or 4 blocks. It might be quicker to do the same thing using updates.


“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Exploring Recursive CTEs by Example Dwain Camps
Post #1479944
Posted Thursday, August 1, 2013 5:19 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, August 7, 2013 10:06 PM
Points: 6, Visits: 22
Thanks All...

I will have a play with all suggested responses and see what I can come up with.

Cheers
Post #1480218
Posted Thursday, August 1, 2013 7:57 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, August 7, 2013 10:06 PM
Points: 6, Visits: 22
Hi All...

Ok, the attached file is where I have got to - can anyone make my code better please?
Is there any way I am able to avoid loops and use a set based approach in its entirity?

For some reason I was unable to add the code to my post, kept getting errors from the web server

Cheers


  Post Attachments 
example.txt (8 views, 2.30 KB)
Post #1480226
Posted Thursday, August 1, 2013 8:28 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Thursday, August 28, 2014 8:30 PM
Points: 3,627, Visits: 5,273
Still would like to see some test data with expected results.

This sounds very similar to a problem I worked out not too long ago. And for that I had a pretty fast solution. I'd just prefer to get it right the first time.

Waiting for my connecting flight to Port Moresby in Brisbane at the moment. I'll check back later.



My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1480233
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse