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
Related Article: using Table name as Variable string
is a Databases discussion thread by Z33shan that has 1 reply, was last updated 1 year ago and has been tagged with the keywords: , microsoft-access.
f_atencia
Junior Poster in Training
59 posts since Aug 2009
Reputation Points: 10
Solved Threads: 4
Skill Endorsements: 0
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