Could insert statements match data from another table - sql

I am trying to do an insert on a table from another table with matched values and IDs.
lets say on table1 there are values of names and IDS. Like John and 55.
I am trying to only insert the 55 into table2 since John is already on table2 but just missing his ID.
I know I can do update statement to update the value for John to 55, but my tables have over 3000 values, and it will be hard to do one at a time:
Anyway I can write a query to enter a value into the other table as long as the names match together?
what I tried so far:
insert into desired_table (id,version,source_id,description,r_id)
SELECT HI_SEQUENCE.nextval,'0', select min (id)
from table
where name in (select name from table2 where table2_name is not null),
table2_name,
table2.r_id from table2 where name is not null;
Issue with this statement is it inserts multiple values, but it only inserts it into where the min ID is.
Anyway I can adjust this and have it pull more than one ID?

Use Merge statement (https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver15)
Merge into Table1 d
Using Table 2 s
on d.name=s.name
when matching then update
age=s.age
when not matching then insert
(col1, col2)
values (s.col1, s.col2);

You might want a trigger to automate the above task.
Create Trigger sample after insert on
Table1 for each row
Begin
Update table2 set table2.age = :NEW.AGE where
table2.id=:NEW.Id
END;

Got this working by generating insert statements and running them with insert all

Related

Why is 'insert into select' statement in SQL inserting as a new row and not inserting correctly?

I have table 1.
I have another empty table 2 with the following columns.
I want to insert into table 2 by selecting from table 1 - so I write the query as:
insert into table2(employee,id,zone,url)
select employee, id, zone, concat('https://',employee,'.com/',id,'?',zone)
from table1
Now my table 2 looks like this,
Now for the authcode column, I do the following and insert it into the table2.
insert into table2(authcode)
SELECT CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
from table2.
But the insert happens differently like this AS AN ENTIRE NEW SET OF ROWS.
Can someone help me to insert the last column to the corresponding rows instead of it creating a new one?
What you should be doing is UPDATE the table to fill the column authcode, but you could do it all in 1 step while you are inserting the rows:
insert into table2(employee,id,zone,url, authcode)
select
employee,
id,
zone,
concat('https://',employee,'.com/',id,'?',zone),
CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(concat('https://',employee,'.com/',id,'?',zone),8,100)),2)
from table1
or if you want to update:
update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
where authcode is null
The result you are seeing is the intended behavior for an INSERT statement. It will always insert new rows.
If you want to modify existing rows your need to use an UPDATE statement.
You can either modify your INSERT to look like what #forpas has posted to get all this work done in one step. Another option is to modify the second INSERT to be an UPDATE like the following:
update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)

Insert Data From One Table to Another Table with default values

The following query works fine but I have a different requirement.
My requirement is as follows.
I have table1 and table2, table1 contains 5 columns and table2 contains 3 columns. Now, we need to pull data from table2 and insert into table1. Here in table2 contains only 3 columns and table1 contains 5 columns. So the rest should insert with some default values.
Could someone help me how to write a query for this.
Change the default values 1 and 2 here
Insert into table1(col1,col2,col3,col4,col5)
select col1,col2,col3,1,2 from table2
You can simply ignore default value colums in Insert statements.
Insert into table1(col1,col2,col3)
select col1,col2,col3 from table2
It'll have default values in col4 & 5.

Save return values from INSERT...RETURNING into temp table (PostgreSQL)

I have a table table1 with columns id,value1 and value2.
Also I have a query
INSERT INTO table1(value1,value2) SELECT value3,value4 FROM table2 RETURNING id
that returns set of ids.
I want to store return values (these ids) in some temp table. Something like that:
INSERT INTO TEMP temp1 INSERT INTO table1(value1,value2) SELECT value3,value4 FROM table2 RETURNING id
How can I do it?
DBMS is PostgreSQL
with inserted as (
INSERT INTO table1 (value1,value2)
SELECT value3,value4
FROM table2
RETURNING id
)
insert into temp
select id
from inserted;
This requires Postgres 9.2 or later.
Two options.
If you need it just for one follow-up query, a with statement (see the horse's answer) is the easiest.
If you need it for more than one follow-up query, the other option is to not use insert ... returning, but rather create table as:
CREATE TEMPORARY TABLE foo AS
SELECT value3,value4 FROM table2
Caveats: if necessary, create the indexes you need on the table -- and analyze it if you do.

Database Triggers: On Insert

This is a simple example.
I want to insert data in Table1 (Name, Age, Sex). This table has an automatically increasing serial#(int) on insertion of data.
I want to put a trigger on Table1 insert, so that after inserting data, it picks up the serial#(int) from Table1 and puts Serial# and Name to Table2 and Serial# and some other data in Table3.
Is it possible via triggers?
or, should I pick (last) Serial from table1 and call insert on other tables by increasing it manually, in same SP I used to insert in Table1?
Which approach is better?
EDIT 1:
Suppose table:
Serial | UID | Name | Age | Sex | DateTimeStamp
(int | uniqueidentifier | nvarchar | smallint | nchar | DateTime )
Default NewID() and Default GetDate() as UID and DateTimeStamp, would INSERTED table have Datetime-Of-Insertion in DatetimeStamp field? Meaning, I originally didn't enter any of Serial, GUID or DatetimeStamp, will they occur in INSERTED table?
EDIT 2:
Can you point me towards good books/articles on triggers. I read mastering SQL server 2005, didn't get much out of it. Thanks!
Sure you can do this with a trigger - something like:
CREATE TRIGGER trg_Table1_INSERT
ON dbo.Table1 AFTER INSERT
AS BEGIN
INSERT INTO dbo.Table2(SerialNo, Name)
SELECT SerialNo, Name
FROM Inserted
INSERT INTO dbo.Table3(SomeOtherCol)
SELECT SomeOtherCol
FROM Inserted
END
or whatever it is you need to do here....
It's important to understand that the trigger will be called once per statement - not once per row inserted. So if you have a statement that inserts 10 rows, your trigger gets called once, and the pseudo-table Inserted will contain those 10 rows that have been inserted in the statement.
Yes, this is possible with triggers.
When you use an INSERT trigger, you have access to the INSERTED logical table that represents the row to be inserted, with the value of the new ID it in.
Yes, it is possible by trigger, but keep in mind that TRIGGER doesn't take any input and doesn't provide any output, so you only can collect your desired data by querying in the trigger, however to satisfy insertion into your Table2 and Table3
CREATE TRIGGER tr_YourDesiredTriggerName ON Table1
FOR INSERT
AS
BEGIN
-- Inserting data to Table2
INSERT INTO Table2( Serial, Name)
SELECT i.Serial, i.Name
FROM Table1 AS t1 INNER JOIN Inserted AS i ON t1.Serial = i.Serial
AND i.Serial NOT IN ( SELECT t2.Serial FROM Table2 AS t2 )
-- Inserting data to Table3
INSERT INTO Table3( Serial, OtherData) -- select from other table
SELECT i.Serial, OtherData
FROM OtherTable AS ot INNER JOIN Inserted AS i ON ot.Serial = i.Serial
AND i.Serial NOT IN ( SELECT t3.Serial FROM Table3 AS t3 )
END
If you don't have control over the source of the insert then use a trigger. If you do have control over the source of the inserts then you can modify your insert process to also add the secondary table rows.
Will you also have control over future inserts? What if another insert gets created for this table? If you use a trigger then the secondary inserts would also get handled automatically. If not then the second insert process could possibly leave out the secondary inserts. Maybe that would be good or bad depending on your application.

Is it wiser to use a function in between First and Next Insertions based on Select?

PROCEDURE add_values
AS BEGIN
INSERT INTO TableA
SELECT id, name
FROM TableC ("This selection will return multiple records")
While it inserts in TableA i would like insert into another table(TableB) for that particular record which got inserted in tableA
Note:The columns in TableA and TableB are different , is it wise to call a function before inserting into TableB as i would like to perform certain gets and sets based on the id inserted in tableA.
If you want to insert a set of rows into two tables, you'd have to store it in a temporary table first and then do the two INSERT statement from there
INSERT INTO #TempTable
SELECT id, name
FROM TableC ("This selection will return multiple records")
INSERT INTO TableA
SELECT (fieldlist) FROM #TempTable
INSERT INTO TableB
SELECT (fieldlist) FROM #TempTable
Apart from Marc_S answer, one more way is
First insert the needed records into Table A from Table C. Then pump the needed records from Table A to Table B
Though many ways has been suggested by many peoples in your question that u asked just 3 hrs ago How to Insert Records based on the Previous Insert