SQL foreach loop - sql

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?

insert SiteCrawl
(
Site_ID
)
select
s.Site_ID
from Site as s
where s.Site_ID not in (select Site_ID from SiteCrawl)

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!

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

insert into SiteCrawls (SiteID)
select SiteID
from Sites

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
;

Related

Using IDs from table and insert into secondary table

Currently I am trying to write a sql statement that selects from one table then uses the primary key to insert into a secondary table. I am having a hard time figuring out how I would do it. This is the select and insert I have right now. The first select will return multiple results. I need to run this nightly so I need to make it dynamic.
SELECT ParentTypeId FROM Config_OrderParentQueueType
INSERT INTO [dbo].[Config_OrderParentQueueTypeNotes]
([ParentTypeId]
,[NoteDate]
,[NoteText]
,[NoteSubmittedById])
VALUES
(This is the ID I need to insert from the select
,GETDATE()
,'Default Note'
,6)
I have tried to mess with rowcount but the IDs are not always sequential. Appreciate any help in advance on how I would do this.
Use insert .. select:
INSERT INTO [dbo].[Config_OrderParentQueueTypeNotes]
([ParentTypeId]
,[NoteDate]
,[NoteText]
,[NoteSubmittedById])
SELECT ParentTypeId, getdate(), 'Default Note', 6
FROM Config_OrderParentQueueType

How to insert new row with id from other table in loop with Postgressql

I would like to insert new row in profit table for each user that exist in db: select id * from users. The number of users is dynamic, so I need to fetch them all. I need some loop in postgres sql. I have problem to figure it out on my own. It would be something like that:
select id * from users as user_ids
for (each userId in user_ids) {
insert into profit (user_id, value) values (userId, 23);
}
Can I ask You for help? I've went for many questions already:
Insert new row with data computed from other rows
postgresSQL insert multiple rows, of id returned from select queries
No luck so far
Thinking in "loops" is almost always wrong when working with SQL. You need to think in terms of sets and how you operate on them. SQL statement describe exactly that: how to retrieve a set and what to do with that set of rows.
In this case, you can use a SELECT statement as the source for an INSERT:
insert into profit (user_id, value)
select id, 23
from users;
Note that you don't have a values clause in this case.

SQL Insert Query With Condition

I am trying to insert values into 1 column of a table when a condition is satisfied.
Note: The table already contains data for all the columns but for 1 which is empty. I would like to insert value into this 1 column depending on the WHERE clause.
I have this query:
INSERT INTO <TABLE_NAME>
(COLUMN_NAME)
(VALUE)
WHERE <CONDITION>
I am getting an exception:
Incorrect Syntax Near WHERE Keyword
I am able to do this using UPDATE:
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
But was wondering why the INSERT query was failing. Any advise appreciated.
As I understand your problem, you already have data in one row, and one column in that row does not have value, so you want to add value in to that column.
This the scenario for Update existing row, not the insert new row. You have to use UPDATE clause when data already present and you want to modify record(s). Choose insert when You want to insert new row in table.
So in your current scenario, Update Clause is your friend with Where Clause as you want to modify subset of records not all.
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
INSERT Clause does not have any Where Clause as per any RDBMS syntax(I think). Insert is condition less sql query, While SELECT, UPDATE, DELETE all are conditional commands, you can add Where Clause in all later ones.
In order to add a value into the one column when the rows are already populated, you will need to use the update statement.
If you need to insert a new row that has a where clause, you will need to use an insert into select statement:
INSERT INTO <table> (<columns>)
SELECT <columns>
FROM <table>
WHERE <condition>;
The SQL Insert dont accept where parameters, you could check this: SQL Insert Definition...
I do not know the whole question of what you want to do, but just using the INSERT statement is not possible, however it is possible to condition the insertion of data into a table, if this data is dependent on another table or comes from another table ... check here... SQL Insert explain in wikipedia
like this:
Copying rows from other tables
INSERT INTO phone_book2
SELECT *
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
or
INSERT INTO phone_book2 ( [name], [phoneNumber] )
SELECT [name], [phoneNumber]
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
Based on your question I have the feeling that you are trying to UPDATE a column in a table rather than insert.
Something like:
UPDATE column SET value WHERE different_column_value = some_value
I know this is kinda late, for those who still want to use the where clause in an insert query, it's kinda possible with a hack.
My understanding is that, you want to insert only if a condition is true. Let's assume you have a column in your database "surname" and you want to insert only if a surname doesn't exist from the table.
You kinda want something like INSERT INTO table_name blha blha blah WHERE surname!="this_surname".
The solution is to make that cell unique from your admin panel.
Insert statement will insert a new record. You cannot apply a where clause to the record that you are inserting.
The where clause can be used to update the row that you want.
update SET = where .
But insert will not have a where clause.
Hope this answers your question
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
I take it the code you included is simply a template to show how you structured your query. See the SO questions here, here and the MSDN question here.
In SQL Server (which uses Transact-SQL aka T-SQL) you need an UPDATE query for INSERT where columns already have values - by using the answer #HaveNoDisplayName gave :)
If you are executing INSERT / UPDATE from code (or if you need it regularly) I would strongly recommend using a stored procedure with parameters.
You could extend the procedure further by adding an INSERT block to the procedure using an IF-ELSE to determine whether to execute INSERT new record or UPDATE an existing, as seen in this SO answer.
Finally, take a look at SQLFiddle for a sandbox playground to test your SQL without risk to your RDMS :-)
Private case I found useful: Conditional insert which avoids duplications:
-- create a temporary table with desired values
SELECT 'Peter' FirstName, 'Pan' LastName
INTO #tmp
-- insert only if row doesn't exist
INSERT INTO Persons (FirstName, LastName)
SELECT *
FROM #tmp t
WHERE NOT EXISTS (SELECT * FROM Persons where FirstName=t.FirstName and LastName=t.LastName)
If the data need to be added for a column for an existing row then it’s UPDATE.
INSERT is creating a new row in the table.
For conditional INSERT, you can use the MERGE command.

INSERT to a table with a sub query

Can I do this in SQL 2005?
SELECT 'C'+inserted.exhid AS ExhId,inserted.exhname AS ExhName,inserted.exhid AS RefID INTO mytable FROM inserted
WHERE inserted.altname IS NOT NULL
It won't work if the table exists, but will create the table if it is non-existent. How do I get it to insert into an existing table?
like this
INSERT INTO mytable
SELECT 'C'+inserted.exhid AS ExhId,inserted.exhname AS ExhName,
inserted.exhid AS RefID FROM inserted
WHERE inserted.altname IS NOT NULL
you also don't need the aliases in this case
SQLMenace's answer is correct. But to add to it, I would suggest that it is a good practice to explicitly list your columns that you are inserting into in the event the table structure/column order ever changes, that way your proc stands a better change of working consistently.
INSERT INTO mytable (
ExhId,
ExhName,
RefID)
SELECT 'C'+inserted.exhid,
inserted.exhname,
inserted.exhid
FROM inserted
WHERE inserted.altname IS NOT NULL
To insert into an existing table, use INSERT INTO instead of `SELECT INTO

Is there a way i can do multiple inserts into one table using a condition?

Is there a way i can do multiple inserts into one table using a condition?
i have a list of subscribers in tbl_subscribers. i have an update on productX so i would like everyone who is subscribes to productX to get a notification. The user_notification table is id PK, user_id, notification_id. The two values i need is product_id (productX) which allows me to find a list of subscribers in tbl_subscribers and the notification_id to insert into the user_notification table.
How can i do this insert using one query? I see you can do a select statement in sqlite http://www.sqlite.org/lang_insert.html but i cannot wrap my head around how i may do this nor seen an example.
I believe you're looking from INSERT SELECT as outlined here:
http://www.1keydata.com/sql/sqlinsert.html
The second type of INSERT INTO allows
us to insert multiple rows into a
table. Unlike the previous example,
where we insert a single row by
specifying its values for all columns,
we now use a SELECT statement to
specify the data that we want to
insert into the table. If you are
thinking whether this means that you
are using information from another
table, you are correct. The syntax is
as follows:
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ... FROM "table2"
insert into user_notification(user_id, notification_id)
select s.user_id, #notification_id
from tbl_subscriber s
where s.product_id = #productX