5

I'm very new at SQL scripts and couldn't figure out how to make a specific for each loop. I need to do something like this:

I have Sites and SiteCrawls tables.

Basically, for every site I need to create a new SiteCrawl and that SiteCrawl's Site_ID column will equal to that site's ID.

How can I do this?

1
  • 4
    One word: don't do it with a foreach loop - SQL is set-based - you think and operate in sets of data. Using RBAR (row-by-agonizing-row) like a foreach loop is very bad for performance Commented Nov 28, 2011 at 16:50

5 Answers 5

12
insert SiteCrawl
(
    Site_ID
)
select
 s.Site_ID
from Site as s
where s.Site_ID not in (select Site_ID from SiteCrawl)
Sign up to request clarification or add additional context in comments.

Comments

4
insert into site_crawl (site_id) values (select site_id from site);

So basically: there is no specific for/each in plain SQL, you handle tables and rows of results always as one statement. So you could also say: there is no way an SQL Statement is something else than a for/each. With that knowledge, you can see that the above query will insert one row into site_crawl for every site_id in the site table. You most likely want to use more values than this, but given the information from your question that is all I can do for you :)

Also: you want to read more about what sql is and how its used.

Have fun, SQL is a lot of fun!

1 Comment

Thank you for your feedback. Like I said, really new at sql and definitely ll work on it.
3

In SQL you typically don't want to loop over every record. It's very inefficient.

You could do something like

insert into SiteCrawl (Site_Id)
select Id from Sites

Comments

1
insert into SiteCrawls (SiteID)
select SiteID 
  from Sites

1 Comment

Just had the same problem, that's helped.
1

you can do it by trigger

CREATE TRIGGER tg AFTER INSERT ON `Sites`
FOR EACH ROW
BEGIN
insert into SiteCrawls(Site_ID) values (NEW.id);
END
;

1 Comment

+1 thats most likely overkill for the given problem, but a nice solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.