Suppose we have two tables “Products” and “Customers” and “ProductsId”
is a foreign key in the “Customers” table from "Products" table.
Condition 1 - For
Single Column update:- Update the “Items” column in Customers from
Products “Items”, where Products.Id equals to Customers.ProductsId.
Query:-
UPDATE Customers cust -------à (“cust” alias name of Customers
table)
SET cust.Items=(SELECT prod.Items
FROM Products prod ---------à (“prod" alias name of the
Products table)
WHERE prod.id=cust.productsid);
Condition 2- For Multiple Column
Update:- Update “Items” and “ExpiryDate” from Products where Products.Id equals to Customers.ProductsId.
Query :-
MERGE
INTO Customers cust -------à (“cust” alias name of Customers table)
USING
(SELECT Id, Items, ExpriyDate FROM Products
)prod ----------à (“Prod” alias name of the subquery
results i.e output of Products table)
ON (cust.productid=prod.id) --------à (Here we are matching the conditions)
WHEN MATCHED THEN
UPDATE
SET cust.item=prod.items,
cust.ExpiryDate=prod.ExpiryDate
/*****Here we can add update multiple
columns, before that we need to select those columns from Products table in the above subquery ******/
;
No comments:
Post a Comment