Copy only certain columns from one table to other and insert defa - sql

I couldn't get any answer googling this question.
I have 2 sql tables, `
Table1 (Id1, Name) and
Table2(Id2, Number)
I would like to copy only one column 'Id1' from table1 to 'Id2' column of table2, while inserting constant value to the Number column.
How can I modify my sql query to achieve this
INSERT INTO Table2
(Id2)
SELECT id1 FROM Table1;

Is this what you want?
INSERT INTO Table2 (Id2, Number)
SELECT id1, <constant value goes here>
FROM Table1;

Taking this a step further an option here would be add a trigger on Table1 to insert into Table2 after insert.
CREATE TRIGGER [dbo].[Table1_CopyId1ColToId2Table2] ON [dbo].[Table1]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.Table2(ID2, Number)
SELECT ID1, <const value> FROM inserted
END
You could also take advantage of after update of the row as well using a trigger. This guarantees even if the row is edited outside the app the trigger still fires.

Related

Could insert statements match data from another table

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

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.

Apache Derby Insert Trigger - Retrieving inserted record

I have a insert trigger for my Derby Database. The point of this trigger is to take everything that is inserted into table_1 and copy that information into table_2. My code works and adds a row to table_2 when I input static numbers, but I cannot figure a way to simply get the value of the row that was just inserted into table_1.
create trigger insert_new_row
after insert on table_1
referencing new as insertedrow
for each row
insert (a,b,c)
values(a,b,c);
In the values part I need the values that were just inserted into table_1 (newsest values). I have also tried- (insertedrow.a) (:insertedrow.a) (new.a) (select a from table_1) and (select a from table_1 where a = insertedrow.a) but none of those work.
Example- if the insert statement reads-
insert into table_1 (a,b,c)
values(1,2,3);
I need to the trigger to insert a row into table_2 with the same values (1,2,3). The collumn names are the same so a trigger of
create trigger insert_new_row
after insert on table_1
referencing new as insertedrow
for each row
insert (a,b,c)
values(1,2,3);
will work but is not practical since I need this to hapen behind the scene and need the values to change with the origional insert statement. Any ideas?
You are missing an into clause for the insert.
The following works for me:
create trigger insert_new_row
after insert on table_1
referencing new as insertedrow
for each row
insert into table_2 (a,b,c)
values( insertedrow.a, insertedrow.b, insertedrow.c);

Trigger to insert values in table2, when values are inserted in table1

I want to write trigger, when values are inserted in table1, same values must get added in table2.
create trigger TestTrigger
on table1
after insert
as
insert into table2
select *
from inserted
go
The assumption here is that table2 and table1 have the same amount of columns with compatible field types (that is needed when you do a "select star" with implicit fields).
If you want to put inserted values that were inserted into table1, you can utilize the inserted table (and deleted as well for DELETE and UPDATE statements).

How can I retrieve the identities of rows that were inserted through insert...select?

I am inserting records through a query similar to this one:
insert into tbl_xyz select field1 from tbl_abc
Now I would like to retreive the newly generated IDENTITY Values of the inserted records. How do I do this with minimum amount of locking and maximum reliability?
You can get this information using the OUTPUT clause.
You can output your information to a temp target table or view.
Here's an example:
DECLARE #InsertedIDs TABLE (ID bigint)
INSERT into DestTable (col1, col2, col3, col4)
OUTPUT INSERTED.ID INTO #InsertedIDs
SELECT col1, col2, col3, col4 FROM SourceTable
You can then query the table InsertedIDs for your inserted IDs.
##IDENTITY will return you the last inserted IDENTITY value, so you have two possible problems
Beware of triggers executed when inserting into table_xyz as this may change the value of ##IDENTITY.
Does tbl_abc have more than one row. If so then ##IDENTITY will only return the identity value of the last row
Issue 1 can be resolved by using SCOPE__IDENTITY() instead of ##IDENTITY
Issue 2 is harder to resolve. Does field1 in tbl_abc define a unique record within tbl_xyz, if so you could reselect the data from table_xyz with the identity column. There are other solutions using CURSORS but these will be slow.
SELECT ##IDENTITY
This is how I've done it before. Not sure if this will meet the latter half of your post though.
EDIT
Found this link too, but not sure if it is the same...
How to insert multiple records and get the identity value?
As far as I know, you can't really do this with straight SQL in the same script. But you could create an INSERT trigger. Now, I hate triggers, but it's one way of doing it.
Depending on what you are trying to do, you might want to insert the rows into a temp table or table variable first, and deal with the result set that way. Hopefully, there is a unique column that you can link to.
You could also lock the table, get the max key, insert your rows, and then get your max key again and do a range.
Trigger:
--Use the Inserted table. This conaints all of the inserted rows.
SELECT * FROM Inserted
Temp Table:
insert field1, unique_col into #temp from tbl_abc
insert into tbl_xyz (field1, unique_col) select field1, unique_col from tbl_abc
--This could be an update, or a cursor, or whatever you want to do
SELECT * FROM tbl_xyz WHERE EXISTS (SELECT top 1 unique_col FROM #temp WHERE unique_col = tbl_xyz.unique_col)
Key Range:
Declare #minkey as int, #maxkey as int
BEGIN TRANS --You have to lock the table for this to work
--key is the name of your identity column
SELECT #minkey = MAX(key) FROM tbl_xyz
insert into tbl_xyz select field1 from tbl_abc
SELECT #maxkey = MAX(key) FROM tbl_xyz
COMMIT Trans
SELECT * FROM tbl_xyz WHERE key BETWEEN #minkey and #maxkey