Foreach insert statement based on where clause - sql

I have a scenario where I have thousands of Ids (1-1000), I need to insert each of these Ids once into a table with another record.
For example, UserCars - has columns CarId and UserId
I want to INSERT each user in my Id WHERE clause against CarId 1.
INSERT INTO [dbo].[UserCars]
([CarId]
,[UserId])
VALUES
(
1,
**My list of Ids**
)
I'm just not sure of the syntax for running this kind of insert or if it is at all possible.

As you write in the comments that my list of Ids is coming from another table, you can simply use select into with a select clause
See this for more information
insert into UserCars (CarID, UserID)
select CarID, UserID
from othertable
In the select part you can use joins and whatever you need, complex queries are allowed as long as the columns in the result match the columns (CarID, UserID)
or even this to keep up with your example
insert into UserCars (CarID, UserID)
select 1, UserID
from dbo.User

if your data exists on a file, you can use BULK INSERT command, for example:
BULK INSERT UserCars
FROM '\\path\to\your\folder\users-cars.csv';
Just make sure to have the same columns structure both in the file and in the table (e.g. CarId,UserId).
Otherwise, follow #GuidoG comment to insert your data from another table:
insert into UserCars (CarID, UserID) select CarID, UserID from othertable

Related

Inserting data into a table(mutliple columns) which has primary key from another data which has data except primary key

I have a table that has 3 columns ID(Primary Key), Name, City.
I need to import data from another table that has only Name and City.
I can write insert into table 1(Name, City) select Name, City from table2.
But then I need ID in table 1 which needs to be inserted using a sequence.
I tried this:
insert into table1(ID, Name,City) values(seq.nextval, select distinct name, city from table2). But I am receiving an error saying an insufficient number of values.
I am trying it in SQL Oracle. Can someone please help me with this?
You are mixing the insert ... values and insert ... select syntax.
You edited your question to include distinct, implying you have duplicate name/city pairs that you want to suppress; but neither version gets the error you reported. If you don't have duplicates then you can just do:
insert into table1(ID, Name,City)
select seq.nextval, name, city from table2;
If you do have duplicates then you can't just add the distinct keyword, but you can use a subquery:
insert into table1 (id, name, city)
select seq.nextval, name, city
from (
select distinct name, city
from table2
);
db<>fiddle
You could also set the ID via a trigger. If you we're on a recent version you could use an identity column instead - but you tagged the question with Oracle 11g, where those are not available.

Dynamically Insert into table while checking if the record already exists

I had some doubts on dynamic insertion of data while doing an insert statement so just wanted to get some assistance from you guys. I have to do multiple insert statements say around 1500 records based on 2 different criteria's below is just a sample of 1 insert statement.
Now while doing an insert statement I want to dynamically assign the USERID's and ROLEid's the 2 columns which you can see in the query below.
So for example where userid IN (500 different userid) and role id in (100 different) ones.
Insert into userrolelist (Userid, Roleid, IsDefault, EffectiveStart,
EffectiveEnd, Clientid, LastmodifiedUserId, LastmodifiedTimestamp)
Values (161514,1011,1,'2016-01-21 00:00:00.001',Null,16785,0,'2016-01-21
00:00:00.001')
I am sure there is a way to do dynamic insertion based on 2 different criteria's I am just confused as to how can I achieve that. Mainly also because for each criteria before insertion I need to check if that userid + roleid combination already exists in the table. Because if I dont check it and still do an insert it will throw an error because there is a constraint based on the 2 fields.
Any help on this matter would be appreciated. Please let me know if the question is not very clear and i can add a bit more explanation if required. Thank you.
You don't say where your lists of user IDs and role IDs are coming from, but because you specify different numbers for each of them, I assume that they are separate lists, rather than a single list of pairs. And I assume that they are stored in tables named userlist and rolelist, respectively. Then you can do the insert as follows:
insert into userrolelist
(Userid, Roleid, IsDefault, EffectiveStart, EffectiveEnd,
Clientid, LastmodifiedUserId, LastmodifiedTimestamp)
select
userid, roleid,
1,'2016-01-21 00:00:00.001',Null,16785,0,
'2016-01-21 00:00:00.001'
from
(select userid, roleid
from userlist
cross join rolelist
) as userrole
where
not exists (select 1 from userrolelist as ur where ur.userid=userrole.userid and ur.roleid=userrole.roleid);
The subquery constructs a list of all possible pairs of users and roles, so if you already have a list of pairs, you can simply use that in place of the subquery.

Inserting the data at a time in 3 tables using an array into Postgresql database

I have to insert the data at a time in 3 tables into PostgreSQL database.
I have to insert data into first and Second table is directly.
But The third table which i received data as array and inserted into 3rd table as same.
Is data inserting as array into PostgreSQL available or possible?
If it possible how can I insert can some correct me
How can i do the same mechanism with Wso2 DSS 3.0.1.
My query is
with first_insert as (insert into sample(name,age)
values(?,?)
RETURNING id
),
second_insert as (insert into sample1(empid,desig)
values((select id from first_insert),?)
RETURNING userid
)
insert into sample2(offid,details)
values((select userid from second_insert),?)
Not sure I understood your question exactly, but at least you could use insert into ... select:
with cte_first_insert as
(
insert into sample1(name, age)
values('John', 25)
returning id
), cte_second_insert as (
insert into sample2(empid, desig)
select id, 1 from cte_first_insert
returning userid
)
insert into sample3(offid, details)
select userid, 'test'
from cte_second_insert;
sql fiddle demo

How to perform insert for each selected row from database

I am trying to make stored procedure that:
- Get list of int rows
select ItemId from Items -- this returns: 1,2,3,4,5,6
In the second part of procedure I have to add row in another table for each of selected number. Something like:
foreach ItemId in previous result
insert into table (ItemIdInAnotherTable) values (ItemId)
UPDATE
I miss one important part from question.
In another part of procedure when I am inserting selected items in another table need to insert a few more columns. Something like this:
insert into dbo.ItemsNotificator
(UserId,ItemId)
(13879, (select ItemId from Items))
So it's not one column. Sorry for confusion :(
Edit :
Assuming that the table [table] already exists, and if User is a constant, then do like so:
INSERT INTO [table](UserId, ItemIdInAnotherTable)
SELECT 13879, ItemId
FROM Items;
If UserId comes from another table entirely, you'll need to figure out what relationship you need between UserId and ItemId. For instance, if all users are linked to all items, then it is:
INSERT INTO [table](UserId, ItemIdInAnotherTable)
SELECT u.UserId, i.ItemId
FROM Items i CROSS JOIN Users u;
If table [table] does NOT already exist, then you can use SELECT INTO, and specify a new table name (e.g. a #temp table stored in tempdb)
SELECT u.UserId, i.ItemId
INTO #tmpNewTable
FROM Items i CROSS JOIN Users u;
The columns in the newly created table will have the names UserId and ItemId and have the same types.
Looks simple to me:
INSERT INTO ItemIdInAnotherTable (ItemId)
SELECT ItemId from Items
That is exactly what a normal insert command does. Just do something like this:
insert into Table (ItemID)
select ItemID from Items;
use INSERT INTO..SELECT statement
INSERT INTO ItemIdInAnotherTable (ItemId)
SELECT ItemId
FROM Items

Insert into select and update in single query

I have 4 tables: tempTBL, linksTBL and categoryTBL, extra
on my tempTBL I have: ID, name, url, cat, isinserted columns
on my linksTBL I have: ID, name, alias columns
on my categoryTBL I have: cl_id, link_id,cat_id
on my extraTBL I have: id, link_id, value
How do I do a single query to select from tempTBL all items where isinsrted = 0 then insert them to linksTBL and for each record inserted, pickup ID (which is primary) and then insert that ID to categoryTBL with cat_id = 88. after that insert extraTBL ID for link_id and url for value.
I know this is so confusing, put I'll post this anyhow...
This is what I have so far:
INSERT IGNORE INTO linksTBL (link_id,link_name,alias)
VALUES(NULL,'tex2','hello'); # generate ID by inserting NULL
INSERT INTO categoryTBL (link_id,cat_id)
VALUES(LAST_INSERT_ID(),'88'); # use ID in second table
I would like to add here somewhere that it only selects items where isinserted = 0 and iserts those records, and onse inserted, will change isinserted to 1, so when next time it runs, it will not add them again.
As longneck said, you cannot do multiple things in one query, but you can in a stored procedure.
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
INSERT INTO linksTBL (link_id,link_name,alias)
SELECT field1, field2, field3
FROM othertable
WHERE inserted=0;
this is not possible to do in a single query. you will have to insert the rows, then run a separate update statement.