Insert into 2 tables with single insert statement - sql

In MSSQL inserting into 2 tables is possible with single insert statement like below(with OUTPUT clause):
insert into Table1(ID1 , Col1)
OUTPUT inserted.ID1, Inserted.Col1
into Table2
values(1,'Col'), (2,'Col2');
Do we have any alternative for this in postgresql? I have tried with below already which is working for me now:
with cte as
(insert into Table1(ID1 , Col1)
values(1,'Col'), (2,'Col2')
returning *)
insert into Table2 select * from cte ;
Please let me know if we have any other alternative. I know about trigger also, but I don't want to use it here.

Related

How to get a key from another table in a insert into... Values SQL statement?

I am not very experienced in SQL statements and I am trying to combine a couple of statements to have less traffic to the db.(and to make sure no other actions can happen inbetween)...
I have two tables:
Table: R_LOTS
a.o. 2 columns: PK_R_LOT and LOTCODE
Table: R_LOTTRACKING
Columns: FK_R_LOT,TIMESTAMP,FK_MAGLOCATIES
I use the statement:
INSERT INTO R_LOTTRACKING (FK_R_LOT,TIMESTAMP,FK_MAGLOCATIES) VALUES (?,CURRENT_TIMESTAMP,?).
On the questionmarks I can fill in the values to send.
However, as you can imagine, I do not have the FK_R_LOT but I have the LOTCODE (of R_LOT).. Of course I can get the FK_R_LOT with a seperate SELECT PK_R_LOT FROM R_LOT WHERE LOTCODE=?; but is there a way to combine these statements?
I have seen some examples but then all information seems to come from the R_LOT table but I could not find a combination of VALUES and SELECT.
Summary:
I know: LOTCODE and FK_MAGLOCATIES
How to combine the statements to insert the row:
INSERT INTO R_LOTTRACKING (FK_R_LOT,TIMESTAMP,FK_MAGLOCATIES) VALUES (?,CURRENT_TIMESTAMP,?)
SELECT PK_R_LOT FROM R_LOT WHERE LOTCODE=?
Use a subquery:
INSERT INTO R_LOTTRACKING ( FK_R_LOT, ... )
VALUES ( (SELECT PK_R_LOT FROM R_LOT WHERE LOTCODE = ?), ... );
or use an insert select:
INSERT INTO R_LOTTRACKING ( FK_R_LOT, ... )
SELECT PK_R_LOT, ... FROM R_LOT WHERE LOTCODE = ?;

Insert Statement - From Temp Table

I am currently trying to insert data into a Redshift table from multiple temporary tables that I have created.
Insert into schema.table1 (
with a as (
select t1.country_code, t1.country_name
from t1
)
select * from a
);
The error that I get on this statement says the following: Amazon Invalid operation: syntax error at or near "as";. What do I need to change in order to be able to insert data from a temp table?
Is it not possible to run the command like this if you have same table structures in both schema.table1 and t1
insert into schema.table1
select t1.country_code, t1.country_name
from t1;
One other thing you might want to check is, in your SQL table1 is in 'schema' but t1 is referred without a schema so it's in public, make sure you don't have two t1s with different structures.
I just tried this and it worked for me.
insert into tempt1 ( with a as (select a from tempt2) select * from a);

Use inserted value as a parameter for other inserts

There is a db2 database with two tables. The first one, table1, has autoincrement column ID. It is the foreign key for the table2.
A am writing an HTML generator for SQL queries. So with some input parameters it generates a query or multiple queries. It is not connected to the database.
What I need is to get that autoincrement field and use it in next queries.
So basically, the scenario is:
insert into table1;
select autogenerated field ID;
insert into table2 using that ID;
insert into table2 using that ID;
...some more similar inserts...
insert into table2 using that ID;
And all that SQL query should be generated and then used as a single SQL script.
I was thinking about something like this:
SELECT ID FROM FINAL TABLE (INSERT INTO Table1 (t1column1, t1column2, etc.)
VALUES (t1value1, t1value2, etc.))
But I don't know, how I can write the result into a variable so I could use it in next queries like this:
INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
VALUES ($ID, t2value1, t2value2, etc.)
I could just paste that select instead of $ID, but the second query can be used several times with the same $ID and different values.
EDIT: DB2 10.5 on Linux.
You can chain several inserts together using CTEs, like so:
WITH idcte (id) as (
SELECT ID FROM FINAL TABLE (
INSERT INTO Table1 (t1column1, t1column2, etc.)
VALUES (t1value1, t1value2, etc.)
)
),
ins1 (id) as (
SELECT foreignKeyCol FROM FINAL TABLE (
INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
SELECT id, t2value1, t2value2, etc.
FROM idcte
)
),
-- more CTEs
SELECT foreignKeyCol FROM FINAL TABLE (
-- your last INSERT ... SELECT FROM
)
Essentially you will have to wrap each INSERT into a SELECT FROM FINAL TABLE for this to work.
Alternatively, you can use a global variable to keep the ID value:
CREATE VARIABLE myNewId INT;
SET myNewId = (SELECT ID FROM FINAL TABLE (
INSERT INTO Table1 (t1column1, t1column2, etc.)
VALUES (t1value1, t1value2, etc.)
));
INSERT INTO Table2 (foreignKeyCol, t2column1, t2column2, etc.)
VALUES (myNewId, t2value1, t2value2, etc.);
DROP VARIABLE myNewId;
This assumes a recent version of Db2 for LUW.

Insert data into multiple tables from one select statement in sql

I need to insert data into two different tables via a select statement.This select statement is calling an inline TVF.
What I have so far is :
INSERT INTO #Temp2 (RowNumber, ValFromUser, ColumnName, ValFromFunc, FuncWeight, percentage)
SELECT
RowNumber, #hospitalname, 'hospitalname',
PercentMatch, #constVal, PercentMatch * #constVal
FROM
dbo.Matchhospitalname (#hospitalname)
But there are certain columns that need to be supplied to a permanent table dbo.Cache.
Above mentioned query is called multiple times in the procedure.
Insert into dbo.Cache(StringSearched, ColName, RowId, PercentMatch)
select
ValFromUser, ColumnName, RowNumber, Max(ValFromFunc) as Percentage
from
#Temp2
group by
ValFromUser, ColumnName, RowNumber
Adding data into dbo.Cache separately as above would make all the previously added values to be added as many times as this statement is executed which is of course not desirable.
May be if it is not possible at all to add data to two tables via one select, we can do something like adding only those rows that were added in last insert statement only ?
Can I get some directions on this, please?
Edit : As suggested, I tried using OUTPUT INTO this way but Group by seems to be at the wrong place.The grouped rowsare to be inserted only in dbo.Cache and not in #Temp2
How do I solve this ?
INSERT INTO #Temp2 (RowNumber,ValFromUser,ColumnName,ValFromFunc,FuncWeight,percentage)OUTPUT
INSERTED.ValFromUser,
INSERTED.ColumnName,
INSERTED.RowNumber,
MAX(INSERTED.ValFromFunc)
INTO dbo.CACHE
(StringSearched, ColName, RowId, PercentMatch)
Group By Inserted.ValFromUser, Inserted.ColumnName, Inserted.RowNumber
SELECT RowNumber,#firstname,'firstname',PercentMatch,#constVal,PercentMatch * #constVal FROM dbo.MatchFirstName(#firstname)
You can do it via an output clause or more typically you can put a trigger on a table. In other words you can create an after insert trigger on temp table '#temp2'. I have never seen a trigger on a temp table but its possible. You will have to recreate the trigger every time the temp table is recreated. Remember that #temp2 will only exist (and be visible) in the session that it is created in.

SQL Server - Contain Multiples Values

I need retrieve a value of columm with SELECT. But, I have multiple values ...
I don't know what the user go select in checkbox...
Ex:
Insert Into MyTable (dados) Values ('a1') I want the result = Angulo 1
Insert Into MyTable (dados) Values ('a2';'a3') I want the result = Angulo 2
Insert into MyTable (dados) Values ('a3'; a1) I want the result = Angulo 3; Angulo 1
Insert into MyTable (dados) Values ('a6'; 'a7'; 'a4') I want the result = Angulo 6; Angulo 7;Angulo4
I am Trying with SELECT CASE WHEN. But it still fails...
I suspect you are asking how to use the IN keyword in your SELECT statements? It is a little unclear what you are trying to do.
Try this:
SELECT *
FROM MyTable
WHERE dados IN ('a6','a7','a4')
Assuming you have a table named MyTable and a column named dados with 3 rows in that table for a6, a7 and a4, this will return all the matches (in this case, all three rows).
Good luck.
When you say:
insert into MyTable(dados)
Values ('a6', 'a7', 'a4')
You are saying "I have one column to put data into called dados." Then, you are providing three values. This will fail in any database (even apart from the fact that the semicolons should be commas).
Perhaps you want:
insert into MyTable(dados)
Values ('a6;a7;a4')
That is only one value, a string.
This suggests a denormalized database. You might want three different rows in a table, one for each value, connected together by some key.
here are some examples if you're using sql server 2008 and above:
if(OBJECT_ID('tempdb..#dados') is not null)
DROP TABLE #dados
select top 100 * INTO #dados FROM
(
values(1,2,3),
(4,5,6),
(7,8,9)
) t(a,b,c)
select * FROM #dados
INSERT INTO #dados (a,b,c)
values(11,22,33),
(44,55,66),
(77,88,99)
SELECT * FROM #dados
INSERT INTO #dados (a,b,c)
SELECT * FROM
(
values(111,222,333),
(444,555,666),
(777,888,999)
) t(a,b,c)
SELECT * FROM #dados
If you want to insert multiple rows (not columns) the syntax is
Insert Into
MyTable (dados)
Values
('a1'),
('a2')
Looks like you're trying to ask for two things.
How to insert multiple values would be done in the following way:
Insert Into MyTable (dados) Values ('a6'),('a7'),('a4')
If you want to return the actual values 'Angulo' + the number, you can use the following:
CREATE TABLE MyTable
(
Dados varchar(255)
)
Insert Into MyTable (dados) Values ('a12')
Insert Into MyTable (dados) Values ('a2'),('a3')
Insert Into MyTable (dados) Values ('a3'),('a1')
Insert Into MyTable (dados) Values ('a6'),('a7'),('a4')
SELECT 'Angulo'+ SUBSTRING(dados,PATINDEX('%[0-9]%',dados),LEN(dados))
FROM MyTable
It will find the first number (assuming it's always the first number you're after) and get the rest of them. It will then append it with the prefix 'Angulo' (e.g Angulo1, Angulo7, etc)
If these aren't what you're after. Please can you explain further what you need.