We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,277 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Using table join instead of cursor

Hi all,

SQL definitely is not my area of expertise, so I need help with something.

Suppose I have 3 tables (I'll try and keep this is as simple as possible):
- User (with UserID). There are 13,000 records
- Status (StatusID as the PK). There are 10 records
- Workflow (WorkflowID as the PK)

Now suppose I have a fourth table:
- Notifications (UserID, StatusID, WorkflowID).

I need to be able to combine all the users, statuses and workflows into this one table so it creates all the possible combinations from the 3 tables listed (meaning there will be 260,000 new records via an insert). Using cursors is too time-consuming and I heard that using Joins will be more effective. Unfortunately, I'm not sure how to start it.

Help is greatly appreciated.

Thanks in advanced

3
Contributors
2
Replies
15 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
f_atencia
Junior Poster in Training
59 posts since Aug 2009
Reputation Points: 10
Solved Threads: 4
Skill Endorsements: 0

Read here: http://msdn.microsoft.com/en-us/library/ms187518.aspx
You should focus on full outer join and before inserting, you should try with just selecting them. You might need to filter the results prior to your insert.

adam_k
Veteran Poster
1,057 posts since Jun 2011
Reputation Points: 274
Solved Threads: 205
Skill Endorsements: 11

I believe what you are looking for is a Cartesian Product among all the tables. You might consider using a "Cross Join" like so:

insert into dbo.notifications
(userid, statusid, workflowid)
select userid, statusid, workflowid
from dbo.users
cross join dbo.status
cross join dbo.workflow

I put together a little test scenario based on your counts above (assuming by your expected insert count and the other counts, there should be 2 workflow rows) and it seemed to work fine.

Hope this helps! Good luck!

BitBlt
Practically a Posting Shark
894 posts since Feb 2011
Reputation Points: 482
Solved Threads: 148
Skill Endorsements: 14

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0609 seconds using 2.65MB