Insert multiple records from joining temporary tables - sql

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

Related

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.

Storing Multiple Insert IDs

After scouring the site (and others...), I cannot find an example of an insert command allowing me to store the "RETURNING" values to a table, CTE, etc. This is what I'd like to do:
WITH insert_rows AS (
INSERT INTO employers (column1, column2, insert_date)
SELECT distinct tc.column1, 'any text', now()
FROM _tmp_employer_updates tc
LEFT JOIN employers e ON e.column1 = tc.column1
WHERE e.column1 IS NULL -- Only insert non-existing employer names
RETURNING employer.row_uuid, employer.column1, employer.column2;
)
SELECT * FROM insert_rows; -- table of returning values
Is there anyway to get an insert command to store it's "returning" values to a table using a CTE? When I try the example above I get:
ERROR: syntax error at or near "INSERT"
LINE 1: ... _tmp_inserted_employers AS WITH insert_rows AS ( INSERT INT...
Thanks in advance...
Remove ; after returning ..., remove alias employer before columns in returning (or change it to employers). Otherwise your query looks good.
Here's an example on sql fiddle.

SQL Query to return rows even if it is not present in the table

This is a specific problem .
I have an excel sheet containing data. Similar data is present in a relational database table. Some rows may be absent or some additional rows may be present. The goal is to verify the data in the excel sheet with the data in the table.
I have the following query
Select e_no, start_dt,end_dt
From MY_TABLE
Where e_no In
(20231, 457)
In this case, e_no 457 is not present in the database (and hence not returned). But I want my query to return a row even if it not present (457 , null , null). How do I do that ?
For Sql-Server: Use a temporary table or table type variable and left join MY_TABLE with it
Sql-Server fiddle demo
Declare #Temp Table (e_no int)
Insert into #Temp
Values (20231), (457)
Select t.e_no, m.start_dt, m.end_dt
From #temp t left join MY_TABLE m on t.e_no = m.e_no
If your passing values are a csv list, then use a split function to get the values inserted to #Temp.
Why not simply populate a temporary table in the database from your spreadsheet and join against that? Any other solution is probably going to be both more work and more difficult to maintain.
You can also do it this way with a UNION
Select
e_no, start_dt ,end_dt
From MY_TABLE
Where e_no In (20231, 457)
UNION
Select 457, null, null

Append one column table to another existing, larger table SQL Server

I have a table name KHA_ID with a column name of KHA_ID. I went to append that to another table named Visits with a column name KHA_ID, and I want to see if I have my SQL right before I run the query
INSERT INTO [databaseName].[dbo].[KHA_ID]
(KHA_ID)
VALUES (KHA_ID,[dbo].Visits)
GO
Thanks!
If KHA_ID is the primary key in KHA_ID table then
INSERT INTO [databaseName].[dbo].[KHA_ID]
(KHA_ID)
SELECT distinct KHA_ID
FROM [dbo].Visits V left outer join
KHA_ID from [databaseName].[dbo].[KHA_ID] K on K.KHA_ID=V.KHA_ID
where K.KHA_ID is null
GO
You need to do it this way:
INSERT INTO [databaseName].[dbo].[KHA_ID]
(KHA_ID)
SELECT KHA_ID
FROM [dbo].Visits
GO

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.