Insert data into multiple tables from one select statement in sql - 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.

Related

CTE: SELECT statement to read rows made by an INSERT Statement

I have a CTE that first inserts rows, and then reads the table with the inserted rows. Right now, the read on the table does not take into account the inserted rows.
The simplest example could be like this:
The Table:
CREATE TABLE mytable (column1 text, column2 text);
The query:
WITH insert_first AS (
INSERT INTO mytable (column1, column2)
VALUES ('value1', 'value2')
RETURNING *
), select_after AS (
SELECT * FROM mytable
LEFT JOIN insert_first ON insert_first.column1 = mytable.column1
) SELECT * FROM select_after
Here, select_after will be empty.
I thought by doing a LEFT JOIN on insert_first, I would hint to SQL to wait for the insert. But, it does not seem to do this.
Is there a way I could make a query that runs over mytable, which sees the inserts made from insert_first?
Here's a playground too: https://www.db-fiddle.com/f/4jyoMCicNSZpjMt4jFYoz5/6796
As Adrian mentioned in the comments, this is not possible:
From docs WITH: The primary query and the WITH queries are all (notionally) executed at the same time. This implies that the effects of a data-modifying statement in WITH cannot be seen from other parts of the query, other than by reading its RETURNING output. If two such data-modifying statements attempt to modify the same row, the results are unspecified.

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);

SQL - Insert Stored Procedure Results into Temp Table

I have a fully working stored procedure grabbing data from different tables using joins. I am currently using the below SELECT statement to select the data I require:
SELECT
ClientReference, ReferenceNumber, Text3,
ReceiptDate, [dbo].[Complaint].[Description],
ActionTaken, dbo.Category.Name, dbo.CategoryOption.FullName,
dbo.Complaint.AuditCreatedBy,
dbo.UserGroup.Name, dbo.Complaint.LoggedByUserId,
dbo.Complaint.LoggedByTime
FROM
dbo.Complaint
Now what I want to be able to do is insert this data into a temporary table. However, INSERT INTO does not work as I have two columns (resulting from my join) called Name.
How would I go about solving this?
Just alias one of the Name columns:
SELECT
ClientReference,
ReferenceNumber,
Text3,
ReceiptDate,
Complaint.Description,
ActionTaken,
Category.Name As CategoryName,
CategoryOption.FullName,
Complaint.AuditCreatedBy,
UserGroup.Name,
Complaint.LoggedByUserId,
Complaint.LoggedByTime
INTO #tempTable
FROM
dbo.Complaint
...

Insert multiple records from joining temporary tables

I need to insert multiple return records from a joining select command to a temporary table. I used the below command . The select statement return two value but when i insert using the below command then the (#TempTableValue) temporary table have nothing.All other field declaration is ok and the joining select command is returning value properly.
INSERT into #TempTableValue DEFAULT values
SELECT #temp1.id,#temp1.DestFieldName,#temp2.FieldValues
FROM #temp2
INNER JOIN #temp1
ON #temp2.FieldName=#temp1.SourceFieldName
select * from #TempTableValue
But the last select command return all Null value. What is the problem here?
Try to remove DEFAULT value as below:
INSERT into #TempTableValue
SELECT #temp1.id,#temp1.DestFieldName,#temp2.FieldValues
FROM #temp2
INNER JOIN #temp1 ON #temp2.FieldName=#temp1.SourceFieldName
from documentation:
DEFAULT VALUES
Forces the new row to contain the default values defined for each
column.
Alright I think I know what's wrong here.
If you use Insert Into #TempTableValue You have to First Create the temp table.
To directly insert your Selection you could use this
Select #temp1.id,#temp1.DestFieldName,#temp2.FieldValues Into #TempTableValue
FROM #temp2
INNER JOIN #temp1
ON #temp2.FieldName=#temp1.SourceFieldName

SQL Insert/Update Issue

I am trying to update one table from another, im able to update fine as long as the customer record exists, but there are some entries that dont.
To solve this i've tried running the following insert
SELECT *
INTO SalBudgetCust
FROM SalBudgetCust_temp
WHERE NOT EXISTS (
SELECT Customer
FROM SalBudgetCust
WHERE Customer = SalBudgetCust_temp.Customer
)
but im prompted with
There is already an object named 'SalBudgetCust' in the database.
Im stuck at this point... could anyone offer a little guideance?
SELECT INTO implicitly creates the table you name. You should instead use INSERT INTO ... SELECT * FROM ..., so that the existing table is used.
It should be INSERT INTO instead of SELECT * INTO ... like
INSERT INTO SalBudgetCust SELECT * FROM SalBudgetCust_temp
WHERE NOT EXISTS
(
SELECT Customer FROM SalBudgetCust WHERE Customer = SalBudgetCust_temp.Customer
)
The general syntax to insert data of one table into another is :
INSERT INTO new_table
SELECT * FROM old_table
WHERE some_condition;
Where, new_table is the table where you want to insert data, old_table is table from where you are fetching data and some_condition is the expression / condition based upon which you want to fetch data from old table.
You may use other clauses like order by, group by, and even sub queries after where clause.
May refer this SQL INSERT INTO and it's subsequent pages.