Using update with an inner join SQL SERVER 2012 - sql

I needed som guidance as to how I can retrieve a column needed from a table with an INNER JOIN and in the same time update and insert a new column into my original table.
This is what I have written so far
SELECT DISTINCT
a.[CustNo],
X.CustomerID
FROM tblA_Add_CustomerID_Column a
INNER JOIN tblX x
ON x.CustomerCode = a.custno
My Table, tblA_Add_CustomerID_Column, only has a column named CustNo, and with the above query, I want to add CustomerID to Table, tblA_Add_CustomerID_Column.
How can I UPDATE and INSERT the column CustomerID from the table tblX?
My normal approach has always been doing the INNER JOIN , then take the results onto the excel sheet, and then import my excel file to the DB.

you can add the column with something like
alter table tblA_Add_CustomerID_Column add CustomerID int
then you can update the table using an update statement, something like
UPDATE tblA_Add_CustomerID_Column
SET CustomerID = x.cusomterID
FROM tblX x
WHERE custno = x.CustomerCode

You could do this instead:
ALTER TABLE tblA_Add_CustomerID_Column
ADD CustomerID INT;
EXEC('
UPDATE a
SET CustomerID = x.cusomterID
FROM tblA_Add_CustomerID_Column a
INNER JOIN tblX x ON x.CustomerCode = a.custno;
');

Related

Full join - two tables with the same attributes and primary keys but different values. What will be the output when I do a full join?

I am writing the trigger function and want to take note of the modification happening on the data. It is for the update, delete and insert. I am trying to use the inserted and deleted tables in the trigger to do a full join on them. But I am not able to figure out if the result.OrderID is the primary key.
select #orderID = isnull (i.OrderID, d.OrderID)
from inserted i
full join deleted d on i.OrderID = d.OrderID;
I think I would use exists:
update SaleOrder
set LastModified = #Lastmodified
where exists (select 1 from inserted i where i.OrderId = SaleOrder.OrderId) or
exists (select 1 from deleted d where d.OrderId = SaleOrder.OrderId) ;
If I understood correct, then this could be better:
UPDATE so
SET LastModified = #LastModified
FROM SaleOrder so
INNER JOIN (SELECT OrderId
FROM Inserted
UNION
SELECT OrderId
FROM Deleted) as t
ON so.OrderId = t.OrderId
Or another way:
UPDATE SaleOrder
SET LastModified = #LastModified
WHERE OrderId IN (SELECT OrderId
FROM Inserted
UNION
SELECT OrderId
FROM Deleted)

assign only particular column values to a temp table from select query

I am having below query that will return 6 columns and i want only assign particular column (converted_skus) results to temporary table and i need to do further processing on that column only ..
I am not sure how can i assign only particular column values to temporary table where as other columns are not needed for further processing
here is my query
SELEct distinct
clpAct.pk_cert,CCM.leg_sku_des,CCM.converted_sku_des,CCM.converted_skus,
esitrans.pk_cert,esitrans.part_id from Clp_Active clpAct
inner join transfertable esitrans
ON clpact.pk_cert = esitrans.pk_cert
INNER JOIN pass_conversion CCM
ON esitrans.part_id = CCM.part_number
where clpAct.subscription_key = #subKey
Would any one please help on this query that would be very grateful to me.
Many thanks in advance
I am using sql server as DB
if you don't need the other columns, then just select your required column only and insert it into the temp table. like this
create table #temp
(
converted_skus varchar(50)
)
insert into #temp
(
converted_skus
)
SELEct distinct
CCM.converted_skus
from Clp_Active clpAct
inner join transfertable esitrans
ON clpact.pk_cert = esitrans.pk_cert
INNER JOIN pass_conversion CCM
ON esitrans.part_id = CCM.part_number
where clpAct.subscription_key = #subKey
now you have only the required column and values in the temp table #temp

Sql Update Count Details after grouping

I have multiple tables in my SQL Server database.
I have one table say Table A which has fields like dispatch,filename,etc.
The second table say Table B has filedetails like filename, dispatchcount, totalcount etc.
There are many other fields in both tables but not relevant to this question.
Requirement is :
I want to update Table B dispatch count after grouping Table A customers where dispatch is Y.
As I want to update the Table B using the result of grouping should I create a temp Table of the result or please guide:
Query:
update Collation_Data set Dqty=T.count1
from (select [collation_code],count(1) as 'count1'
FROM [Tatkal].[dbo].[Tatkal_Merge] T
where Dscan='Y'
group by [collation_code]) where srno=T.[collation_code]
In SQL Server, you can use a join with an aggregation query. I want to point out that you should use left join if you want to update all rows in collation_data, even those with no matches:
update c
set c.Dqty = cm.cnt
from Collation_Data c left join
(select collation_code, count(*) as cnt
from [Tatkal].[dbo].[Tatkal_Merge] m
where Dscan = 'Y'
group by collation_code
) cm
on c.srno = cm.collation_code;
You can also do this with a correlated subquery:
update Collation_Data c
set Dqty = (select count(*)
from [Tatkal].[dbo].[Tatkal_Merge] m
where m.Dscan = 'Y' and m.collation_code = c.collation_code
);
This can be quite efficient with an index on Tatkal_Merge(collation_code, Dscan).
I want to update the Table B using the result of grouping should I create a temp Table of the result or please guide
update c
set c.Dqty=T.count1
from Collation_Data c
join
(select [collation_code],count(1) as 'count1'
FROM [Tatkal].[dbo].[Tatkal_Merge]
where Dscan='Y'
group by [collation_code])t
on c.srno=T.[collation_code]

How to update ms access database table using update and sum() function?

I have Two tables in my access database
table1(ID,productname,qunatity,remainder)
table2(ID,productname,sales)
these tables are related together using "product name" ,How can I update"reminder" from table1 with the value of "quantity form first table - Sum(sales) from second table"
Because update queries in MS Access require updateable status, you cannot use a direct inner join on an aggregate query. Consider using the MS Access DSum() function:
UPDATE table1
SET table1.remainder = table1.quantity -
DSum("Sales", "table2", "ProductName='" & table1.ProductName & "'")
Perform an update join by getting the SUM() first like
UPDATE a
SET a.remainder = x.SaleTotal
FROM table1 a
INNER JOIN (SELECT productname, SUM(sales) AS SaleTotal
FROM TABLE2 GROUP BY productname) x
ON a.productname = x.productname;
When you say that it's linked by the productname field please tell me in table 1 that is a foreign key. Since you already have an ID in table 2 there's no reason not to use that ID as the foreign key in table 1.
If you were to do that the update would be as simple as this:
update table1
set table1.quantity = table1.quantity - SUM( table2.sales )
from table1
inner join table2 on table1.productID = table2.productID
where table1.productID = 1;

SQL Server Update with Inner Join

I have 3 tables (simplified):
tblOrder(OrderId INT)
tblVariety(VarietyId INT,Stock INT)
tblOrderItem(OrderId,VarietyId,Quantity INT)
If I place an order, I drop the stock level using this:
UPDATE tblVariety
SET tblVariety.Stock = tblVariety.Stock - tblOrderItem.Quantity
FROM tblVariety
INNER JOIN tblOrderItem ON tblVariety.VarietyId = tblOrderItem.VarietyId
INNER JOIN tblOrder ON tblOrderItem.OrderId = tblOrder.OrderId
WHERE tblOrder.OrderId = 1
All fine, until there are two rows in tblOrderItem with the same VarietyId for the same OrderId. In this case, only one of the rows is used for the stock update. It seems to be doing a GROUP BY VarietyId in there somehow.
Can anyone shed some light? Many thanks.
My guess is that because you have shown us simplified schema, some info is missing that would determine why have the repeated VarietyID values for a given OrderID.
When you have multiple rows, SQL Server will arbritrarily pick one of them for the update.
If this is the case, you need to group first
UPDATE V
SET
Stock = Stock - foo.SumQuantity
FROM
tblVariety V
JOIN
(SELECT SUM(Quantity) AS SumQuantity, VarietyID
FROM tblOrderItem
JOIN tblOrder ON tblOrderItem.OrderId = tblOrder.OrderId
WHERE tblOrder.OrderId = 1
GROUP BY VarietyID
) foo ON V.VarietyId = foo.VarietyId
If not, then the OrderItems table PK is wrong because if allows duplicate OrderID/VarietyID combinations (The PK should be OrderID/VarietyID, or these should be constrained unique)
From the documentation UPDATE
The results of an UPDATE statement are
undefined if the statement includes a
FROM clause that is not specified in
such a way that only one value is
available for each column occurrence
that is updated (in other words, if
the UPDATE statement is not
deterministic). For example, given the
UPDATE statement in the following
script, both rows in table s meet the
qualifications of the FROM clause in
the UPDATE statement, but it is
undefined which row from s is used to
update the row in table t.
CREATE TABLE s (ColA INT, ColB DECIMAL(10,3))
GO
CREATE TABLE t (ColA INT PRIMARY KEY, ColB DECIMAL(10,3))
GO
INSERT INTO s VALUES(1, 10.0)
INSERT INTO s VALUES(1, 20.0)
INSERT INTO t VALUES(1, 0.0)
GO
UPDATE t
SET t.ColB = t.ColB + s.ColB
FROM t INNER JOIN s ON (t.ColA = s.ColA)
GO
You are doing an update. It will update once.
Edit: to solve, you can add in a subquery that will group your orderitems by orderid and varietyid, with a sum on the amount.