need clarification on where not exists clause - sql

I am trying to insert only those records into #AltDealNames table for which DealName exists in #DistDeal table but not in #AltDealNames table. For this I am trying not exists clause. But it is not working as expected. Query is simply dumping records into #AltDealNames table.
insert into #AltDealNames
select d.DealName, d.ManagerScrubbed, d.BbgDealName, t.TrancheName, t.StreetCusip, t.ISIN, t.BbgTrancheName
from metric..Deal d join metric..Tranche t on d.DealName = t.DealName
where not exists(select 1 from #DistDeal dd join #AltDealNames ad on ad.DealName = dd.DealName)
Please help me to know if I am doing something wrong while building query.

If I understand correctly, you want an exists clause for #DistDeal and a not exists for #AltDealNames:
insert into #AltDealNames
select d.DealName, d.ManagerScrubbed, d.BbgDealName, t.TrancheName,
t.StreetCusip, t.ISIN, t.BbgTrancheName
from metric..Deal d join
metric..Tranche t
on d.DealName = t.DealName
where exists (select 1 from #DistDeal dd where dd.DealName = d.DealName) and
not exists (select 1 from #AltDealNames ad on ad.DealName = dd.DealName);
Note: when using insert, you should always include the list of column names.

Depending on how the optimizer sets up the actual physical query, the "where not exists" clause might run first, before anything is inserted by this query. Ie., it would only filter on values in #AltDealNames that were there from a previous query.
If you're trying to avoid inserting DealName values that are in #DistDeal, then maybe you want:
insert into #AltDealNames
select d.DealName, d.ManagerScrubbed, d.BbgDealName, t.TrancheName,
t.StreetCusip, t.ISIN, t.BbgTrancheName
from metric..Deal d
join metric..Tranche t on d.DealName = t.DealName
where not exists(select 1 from #DistDeal dd
where d.DealName = dd.DealName) -- Changed line

Related

Using a LEFT OUTER JOIN WHERE then updating same data

I have two databases running on MSSQL 2005, SOURCE and DESTINATION, which have the same structure and tables in them.
I'm trying to update data from s to d.
In this example, I'm trying to copy data from s to d using a join and only bringing across entries which aren't already in d.
I'm then trying to update the same records just inserted with vales thus:
INSERT DESTINATION.ITEM_REPLENISH_VENDOR ([ITEM_CODE],[VEND_CODE],[PRIMARY_VENDOR],[PURCHASE_MEASURE],[STD_COST],[LAST_COST],[EOQ],[VENDOR_PART_NO],[LEAD_TIME],[COST])
SELECT s.[ITEM_CODE],s.[VEND_CODE],s.[PRIMARY_VENDOR],s.[PURCHASE_MEASURE],s.[STD_COST],s.[LAST_COST],s.[EOQ],s.[VENDOR_PART_NO],s.[LEAD_TIME], s.[COST] FROM SOURCE.dbo.ITEM_REPLENISH_VENDOR s
LEFT OUTER JOIN DESTINATION.dbo.ITEM_REPLENISH_VENDOR d ON (d.ITEM_CODE = s.ITEM_CODE)
WHERE d.ITEM_CODE IS NULL
UPDATE DESTINATION.dbo.ITEM_REPLENISH_VENDOR
SET VEND_CODE='100004', PRIMARY_VENDOR='T',STD_COST='0',LAST_COST='0',COST='0'
WHERE
My issue is once I reach the second WHERE I don't know how to refer to the data I've just updated. This script is going to run either every day at a set time and I don't want to overwrite that whole column with those values, just the entries that have been inserted on this execution.
It looks like you want the output clause This will let you stash away the inserted values.
-- item_code needs to have the same type as the source table
declare #inserted table (item_code int not null primary key);
insert destination.item_replenish_vendor (
[item_code], [vend_code], [primary_vendor],
[purchase_measure], [std_cost], [last_cost],
[eoq], [vendor_part_no], [lead_time],[cost]
) -- save inserted values
output
inserted.item_code into #inserted
select
s.[item_code], s.[vend_code], s.[primary_vendor],
s.[purchase_measure], s.[std_cost], s.[last_cost],
s.[eoq], s.[vendor_part_no], s.[lead_time], s.[cost]
from
source.dbo.item_replenish_vendor s
left outer join
destination.dbo.item_replenish_vendor d
on d.item_code = s.item_code
where
d.item_code is null;
update
d
set
vend_code = '100004',
primary_vendor = 'T',
std_cost = '0',
last_cost = '0,
cost = '0'
from
destination.dbo.item_replenish_vendor d
inner join
#inserted i
on d.item_code = i.item_code;
In this case, you could just put constant values in the insert statement, instead of doing things in two steps...
In the example you have:
UPDATE DESTINATION.dbo.ITEM_REPLENISH_VENDOR
SET VEND_CODE='100004', PRIMARY_VENDOR='T',STD_COST='0',LAST_COST='0',COST='0'
If your VEND_CODE, PRIMARY_VENDOR, STD_COST, LAST_COST, COST are always going to be a static value, you could just put them into the first query.
INSERT DESTINATION.ITEM_REPLENISH_VENDOR ([ITEM_CODE],[VEND_CODE],[PRIMARY_VENDOR],[PURCHASE_MEASURE],[STD_COST],[LAST_COST],[EOQ],[VENDOR_PART_NO],[LEAD_TIME],[COST])
SELECT s.[ITEM_CODE],'100004','T',s.[PURCHASE_MEASURE],'0','0',s.[EOQ],s.[VENDOR_PART_NO],s.[LEAD_TIME], '0'
FROM SOURCE.dbo.ITEM_REPLENISH_VENDOR s
LEFT OUTER JOIN DESTINATION.dbo.ITEM_REPLENISH_VENDOR d ON (d.ITEM_CODE = s.ITEM_CODE)
WHERE d.ITEM_CODE IS NULL
but if they do need to be calculated after insert, then I agree with Laurence's approach.

How to copy or update from one table to another table

I have two tables. user and user_new
the user contains the old data.
the user_new contains the new data.
I want to sync the user_new to user.
if the data exist in user_new and not exist in user,then insert to user.
if the data exist in user and user_new, then update.(compare with the column id)
what's the fast sql to do it?
This works on any server version -
-- 1) Insert new record
INSERT INTO old_table(id, column)
SELECT n.id, n.column
FROM new_table n
LEFT JOIN old_table o ON n.id = o.id
WHERE o.id IS NULL
-- 2) Update existed record
UPDATE o
SET column = n.column
FROM old_table o
JOIN new_table n ON n.id = o.id
From Sql Server 2008 onwards you can use Merge syntax
MERGE user target
USING user_new source
ON taget.ID = source.ID
WHEN MATCHED THEN
UPDATE
SET target.Column= source.Column1,target.column2=source.column2
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID,Column1,Column2)
VALUES (source.ID,source.column1,source.column2);
or you can use the below query
INSERT INTO user(ID,column1,column2)
SELECT ID,column1,column2 FROM user_new AS source
WHERE NOT EXISTS (SELECT * FROM user WHERE ID = source.ID);
UPDATE target SET ...
FROM user AS target
INNER JOIN user_new AS source
ON target.ID = source.ID;
Sounds like you might need a Merge if you have sql server 2008+.
You can't do insert and update in a single query you have to do in seperate
select * from user where user_id not in (select user_new.user_id from user_new )
this query results the data for insert query similarly u have to update by replacing not in to in

SQLite inner join - update using values from another table

This is quite easy and has been asked multiple times but I can't get it to work.
The SQL query I think should work is:
UPDATE table2
SET dst.a = dst.a + src.a,
dst.b = dst.b + src.b,
dst.c = dst.c + src.c,
dst.d = dst.d + src.d,
dst.e = dst.e + src.e
FROM table2 AS dst
INNER JOIN table1 AS src
ON dst.f = src.f
Using the update statement it is not possible because in sqlite joins in an update statement are not supported. See docs:
update statement
If you only wanted to update a single column to a static value, you could use a subquery in the update statement correctly. See this example: How do I make an UPDATE while joining tables on SQLite?
Now in your example, making an assumption that there is a unique key on "column f" - a workaround/solution I have come up with is using the replace statement:
replace into table2
(a, b, c, d, e, f, g)
select src.a, src.b, src.c, src.d, src.e, dest.f, dest.g
from table1 src
inner join table2 dest on src.f = dest.f
I also added an extra column to table2 "column g" to show how you'd "update" only some of the columns with this method.
One other thing to be cautious about is if you use "PRAGMA foreign_keys = ON;" it's possible to have issues with this as the row is effectively deleted and inserted.
I came up with an alternative technique using a TRIGGER and "reversing" the direction of the update, albeit at the cost of a dummy field in the source table.
In general terms, you have a Master table and an Updates table. You want to update some/all fields of records in Master from the corresponding fields in Updates linked by a key field Key.
Instead of UPDATE Master SET ... FROM Master INNER JOIN Updates ON Mater.Key = Updates.Key you do the following:
Add a dummy field TriggerField to the Updates table to act as the focus of the trigger.
Create a trigger on this field:
CREATE TRIGGER UpdateTrigger AFTER UPDATE OF TriggerField ON Updates
BEGIN
UPDATE Master SET
Field1 = OLD.Field1,
Field2 = OLD.Field2,
...
WHERE Master.Key = OLD.Key
END;
Launch the update process with the following:
UPDATE Updates SET TriggerField = NULL ;
Notes
The dummy field is merely an anchor for the trigger so that any other UPDATE Updates SET ... won't trigger the update into Master. If you only ever INSERT into Updates then you don't need it (and can remove the OF TriggerField clause when creating the trigger).
From some rough-and-ready timings, this seems to work about the same speed as REPLACE INTO but avoids the feels-slightly-wrong technique of removing and adding rows. It is also simpler if you are only updating a few fields in Master as you only list the ones you want to change.
It is orders of magnitude faster than the other alternative I've seen to UPDATE ... FROM which is:
UPDATE Master SET
Field1 = ( SELECT Field1 FROM Updates WHERE Mater.Key = Updates.Key ),
Field1 = ( SELECT Field1 FROM Updates WHERE Mater.Key = Updates.Key ),
...
;
Updating six fields over 1700 records was roughly 0.05s for Tony and my methods but 2.50s for the UPDATE ... ( SELECT... ) method.
AFTER UPDATE triggers on Master seem to fire as expected.
As Tony says, the solution is the replace into way but you can use the sqlite hidden field rowid to simulate full update with join like:
replace into table2
(rowid,a, b, c, d, e, f, g)
select dest.rowid,src.a, src.b, src.c, src.d, src.e, dest.f, dest.g
from table1 src
inner join table2 dest on src.f = dest.f
With this you recreate full rows if you don't have primary key for the replace or as standard method to do the updates with joins.
SQLITE does not support UPDATE with INNER JOIN nor do several other DB's. Inner Joins are nice and simple however it can be accomplished using just a UPDATE and a subquery select. By using a where clause and the 'IN' with a subquery and a additional subquery for the 'SET' the same result can always be accomplished. Below is how it's done.
UPDATE table2
SET a = a + (select a from table1 where table1.f = table2.f),
b = b + (select b from table1 where table1.f = table2.f),
c = c + (select c from table1 where table1.f = table2.f),
d = d + (select d from table1 where table1.f = table2.f),
e = e + (select e from table1 where table1.f = table2.f)
WHERE RowId IN (Select table2.RowId from table1 where table1.f = table2.f)
Use below query:
UPDATE table2
SET a = Z.a,
b = Z.b,
c = Z.c,
d = Z.d,
e = Z.e
FROM (SELECT dst.id,
dst.a + src.a AS a,
dst.b + src.b AS b,
dst.c + src.c AS c,
dst.d + src.d AS d,
dst.e + src.e AS e
FROM table2 AS dst
INNER JOIN table1 AS src ON dst.f = src.f
)Z
WHERE table2.id = z.id

Copy values from one table to another in SQL

I have 2 tables. I need to update all rows of table 1 with the values in specific columns from table 2. They have the same structure.
UPDATE #TempTable
SET [MyColumn] =
(
SELECT [MyColumn]
FROM
[udf_AggregateIDs] (#YearId) AS [af]
INNER JOIN [MyForm] ON
(
[af].[FormID] = [MyForm].[FormID] AND
[af].[FormID] = #MyFormId
)
WHERE [Description] = [MyForm].[Description]
)
I get an error saying Subquery returned more than 1 value. I only added the where clause in because i thought sql is struggling to match the rows, but both tables have the same rows.
It should return multiple values because i'm trying to copy across all rows for MyColumn from the one table to the other.
Ideas?
is Description unique ?
select [Description], count(*) from [MyForm] group by [Description] having count(*)>1
You don't need a sub query..just join the tables..
same type of question has been answered here. Hope it helps.
Have to guess here because your query isn't self-documenting. Does MyColumn come from the function? Does #TempTable have a description column? Who knows, because you didn't prefix them with an alias? Try this. You may have to adjust since you know your schema and we don't.
UPDATE t
SET [MyColumn] = func.MyColumn -- have to guess here
FROM dbo.[udf_AggregateIDs] (#YearId) AS func
INNER JOIN dbo.MyForm AS f
ON func.FormID = f.FormID
INNER JOIN #TempTable AS t
ON t.Description = f.Description -- guessing here also
WHERE f.FormID = #MyFormID;

Update table a from table b where (conditions)

Evening all,
Actually, it's night. About 11pm. My brain is shutting down and I need a bit of help so I can finish and go home :)
I have two tables - table a and table b.
I need to update a field in table a with the value from a field in table b when two other fields match. The tables don't have a unique id for each record :(
Basically, I want to do this:
update a
set importantField =
(select b.importantfield
from b
where a.matchfield = b.matchfield
and a.matchfield2 = b.matchfield2
)
where a.matchfield = b.matchfield
and a.matchfield2 = b.matchfield2
Or at least... I think that's what I want to do...
Can someone help me out, please?
You can do this via a join in the update:
Update a
Set a.importantField = b.importantField
From a Join b
On a.matchfield = b.matchfield
And a.matchfield2 = b.matchfield2
Use:
UPDATE TABLE_A
SET importantField = (SELECT b.importantfield
FROM TABLE_B b
WHERE b.matchfield = matchfield
AND b.matchfield2 = matchfield2)
SQL Server doesn't support table aliases on the table being updated, but the above is a correlated query - those fields without the table alias b attached will serve values from TABLE_A because it doesn't have an alias.
The only issue beyond that is if there are multiple b.importantfield values for records with the matching records to TABLE_A. Use:
UPDATE TABLE_A
SET importantField = (SELECT TOP 1
b.importantfield
FROM TABLE_B b
WHERE b.matchfield = matchfield
AND b.matchfield2 = matchfield2)
..but you should use an ORDER BY as well or you'll get any random b.importantfield value.