insert into existing temp table in sql server - sql-server

I have created a temp table in sql server and inserted values to it.
If the values of a particular column are null i need to fill using some values from another table. How to query this?
sample data given below.
select 'name' as name,3 as age,'email' as email into #tmp1 from table1
Now if the column age is empty i need to insert a value to the column age to all the existing records in tmp1.
INSERT INTO #tmp1 (age)SELECT age AS [age] FROM table2 WHERE name=#name
But it inserts a new record.
please help.

You want UPDATE, not INSERT
Something like this:
UPDATE #tmp1
SET age = Table2.Age
FROM table2
WHERE #tmp1.Age IS NULL
AND #tmp1.Name = Table2.Name

You need to do update not Insert:
Update a
a.age = b.age
from
(select id,age from table where age is null) a
inner join
table b
ON a.id = b.id

Related

I only want to insert data from table2 to table1 that doesn't exist already on MS SQL

I have a table named MarketData, and I am trying to pull certain columns from MarketData and insert them to another table called Payups. But I only want to insert data that doesn't repeat onto Payups.
Keep in mind, the MarketData table includes more columns that I don't need in the PayUps column.
After I execute the query below, it keeps on adding records that are similar.
INSERT INTO [MortgagePipeline].[dbo].[PayUps]
(
RecordDate
,Investor
,Product
,MinCoupon
,[Payup(bcp)]
)
SELECT DISTINCT t1.ContractDate
,t1.SourceCode
,t1.ProductName
,t1.ContractInterestRate
,t1.ContractPrice
FROM [MortgagePipeline].[dbo].[MarketData] t1
WHERE NOT EXISTS
(
SELECT RecordDate
,Investor
,Product
,MinCoupon
,[Payup(bcp)]
FROM [MortgagePipeline].[dbo].[PayUps] t2
WHERE t2.RecordDate = t1.ContractDate
AND t2.Investor = t1.SourceCode
AND t2.Product = t1.ProductName
AND t2.MinCoupon = t1.ContractInterestRate
AND t2.[Payup(bcp)] = t1.ContractPrice
AND t2.MaxCoupon = NULL
AND t2.PayupName = NULL
)
RecordDate, Investor , Product ,MinCoupon ,[Payup(bcp)], MaxCoupon PayupName are all the columns that exists on Payups. all of The values of those columns are inserted from the MarketData Table except from MaxCoupon and PayupName that remain null.

Best way to attack a confusing SQL issue in inserting data into a TEMP table

I'm working in SQL Server 2016. Confusing problem with SQL issue. I have a TEMP table that contains unique rows. I have to insert 5 PRODUCTID values for each row each row based on another column value, AgentNo, in this temp table. The PRODUCTID value, there are 5 of them, comes from another table but there is no relationship between the tables. So my question is how do I insert a row for each ProductID into this temp table for each unique row that is currently in the temp table.
Here is a pic of the TEMP table that requires 5 rows for each:
Here is a pic of what I'm needing to come away with:
Here is my SQL code for both TEMP tables:
IF OBJECT_ID('tempdb..#tempTarget') IS NOT NULL DROP TABLE #tempTarget
SELECT 0 as ProductID, 1 as [Status], a.AgentNo, u.UserID, u.[Password], 'N' as AdminID, tel.LocationSysID --, tel.OwnerID, tel.LocationName, a.OwnerSysID, a.AgentName
INTO #tempTarget
FROM dbo.TEST_EvalLocations tel
INNER JOIN dbo.AGT_Agent a
ON tel.LocationName = a.AgentName
INNER JOIN dbo.IW_User u
ON a.AgentNo = u.UserID
WHERE tel.OwnerID = 13313
AND tel.LocationSysID <> 15434;
SELECT * FROM #tempTarget WHERE LocationSysID NOT IN (15425, 15434);
GO
-- Create source table
IF OBJECT_ID('tempdb..#tempSource') IS NOT NULL DROP TABLE #tempSource
SELECT DISTINCT lpr.ProductID
INTO #tempSource
FROM dbo.Eval_LocationProductRelationship lpr
WHERE lpr.ProductID IN (16, 15, 13, 14, 12) --BETWEEN 15435 AND 15595
Sorry I could not get this into a DDL file as these are TEMP tabless. Any help/direction would be appreciated. Thanks.
CROSS JOIN will be the best solution for your case.
If you only want 5 rows for each data in First table means, simply use the below cross join query.
SELECT B.ProductID,
A.[Status],
A.AgentNo,
A.UserID,
A.[Password] AS Value,
A.AdminID,
A.LocationSysID
FROM #tempTarget A
CROSS JOIN tempSource B
If you want additional row with 0, then you have to insert a 0 into your second temp table and use the same query.
INSERT INTO #tempSource SELECT 0
If i understand correctly following is the scenario,
One Temp table has all the content.
select * from #withoutProducts
product table
select * from #products
Then following is the query your are looking for
select a.ProductID,[Status],AgentNo,UserID,[value]
from #products a cross join #withoutProducts b
order by AgentNO,a.productID

Show all and only rows in table 1 not in table 2 (using multiple columns)

I have one table (Table1) that has several columns used in combination: Name, TestName, DevName, Dept. When each of these 4 columns have values, the record is inserted into Table2. I need to confirm that all of the records with existing values in each of these fields within Table1 were correctly copied into Table 2.
I have created a query for it:
SELECT DISTINCT wr.Name,wr.TestName, wr.DEVName ,wr.Dept
FROM table2 wr
where NOT EXISTS (
SELECT NULL
FROM TABLE1 ym
WHERE ym.Name = wr.Name
AND ym.TestName = wr. TestName
AND ym.DEVName = wr.DEVName
AND ym. Dept = wr. Dept
)
My counts are not adding up, so I believe that this is incorrect. Can you advise me on the best way to write this query for my needs?
You can use the EXCEPT set operator for this one if the table definitions are identical.
SELECT DISTINCT ym.Name, ym.TestName, ym.DEVName, ym.Dept
FROM table1 ym
EXCEPT
SELECT DISTINCT wr.Name, wr.TestName, wr.DEVName, wr.Dept
FROM table2 wr
This returns distinct rows from the first table where there is not a match in the second table. Read more about EXCEPT and INTERSECT here: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-except-and-intersect-transact-sql?view=sql-server-2017
Your query should do the job. It checks anything that are in Table1, but not Table2
SELECT ym.Name, ym.TestName, ym.DEVName, ym.Dept
FROM Table1 ym
WHERE NOT EXISTS (
SELECT 1
FROM table2
WHERE ym.Name = Name AND ym.TestName = TestName AND ym.DEVName = DEVName AND ym. Dept = Dept
)
If the structure of both tables are the same, EXCEPT is probably simpler.
IF OBJECT_ID(N'tempdb..#table1') IS NOT NULL drop table #table1
IF OBJECT_ID(N'tempdb..#table2') IS NOT NULL drop table #table2
create table #table1 (id int, value varchar(10))
create table #table2 (id int)
insert into #table1(id, value) VALUES (1,'value1'), (2,'value2'), (3,'value3')
--test here. Comment next line
insert into #table2(id) VALUES (1) --Comment/Uncomment
select * from #table1
select * from #table2
select #table1.*
from #table1
left JOIN #table2 on
#table1.id = #table2.id
where (#table2.id is not null or not exists (select * from #table2))

sql insert query clause

I have a table A which contains fields
ChangeID DistributionID OutletBrandID
and Table B contains
ID DistributionID OutletBrandID
I need to insert data in table A from table B only if the distributionID and OutletBrandID combination doesn't exist already. Therefore I can't simply use the IN clause as it needs to be a combination.
Assuming that ChangeID and ID should match between the tables:
INSERT INTO TableA (ChangeID, DistributionID, OutletBrandID)
SELECT b.ID, b.DistributionID, b.OutletBrandID FROM TableB b
LEFT OUTER JOIN TableA a ON a.DistributionID=b.DistributionID
AND a.OutletBrandID = b.OutletBrandID
WHERE
a.OutletBrandID IS NULL
AND
a.DistributionID IS NULL

insert results of join in SQL server 2005

I have two tables with more than 800 rows in each.Table names are 'education' and 'sanitation'.The column name 'ID' is common in both the tables.Now i want to join these both tables as full outer join and i want to save the results of this table as a new table.I can join it very easily,But how to save those data's as a new table.Please help Me.
select * into bc from education e join sanitation s on e.id=s.id
I have around 30 columns in each table.So i can not explicitly create table schema for a new table.
I want all the columns from both tables.I have 20 tables with each 800 rows.From this 20 tables i want to make one master table taking 'ID' as primary key in all.
Sample Code:
Table one:
create table dummy1(
id int , fname varchar(50)
)
insert into dummy1 (id,fname) values (1,'aaa')
insert into dummy1 (id,fname) values (2,'bbb')
insert into dummy1 (id,fname) values (3,'ccc')
insert into dummy1 (id,fname) values (3,'ccc')
Table Two
create table dummy2(
id int , lname varchar(50)
)
insert into dummy2 (id,lname) values (1,'abc')
insert into dummy2 (id,lname) values (2,'pqr')
insert into dummy2 (id,lname) values (3,'mno')
Now Create new table 3
create table dummy3(
id int , fname varchar(50),lname varchar(50)
)
Insert Query for table 3 look like
insert into dummy3 (id,fname,lname)
(select a.id,a.fname,b.lname from dummy1 a inner join dummy2 b on a.id=b.id)
Table 3 will contain table1, table2 data
Follow below:
SELECT t1.Column1, t2.Columnx
INTO DestinationTable
FROm education t1
INNER JOIN sanitation t2 ON t1.Id = t2.Id
EDIT:
SELECT * will not work for you because you have a column ID which exists in both the tables. So the above solution will work you.
EDIT:
1- You can temporarily rename the Id column in one table, then try
2- SELECT *
INTO DestinationTable
FROm education t1
INNER JOIN sanitation t2 ON t1.Id = t2.Id
3- Revert the column name back to Id.

Resources