Link to home
Start Free TrialLog in
Avatar of 25112
25112

asked on

DML on CTE?

what DMLs can do inside a CTE resultset?
Avatar of MohitPandit
MohitPandit
Flag of India image

Hello,

You can have
SELECT
statement inside of CTE parenthesis but after close CTE parenthesis then you can have
INSERT, DELETE, UPDATE, SELECT

For example,
USE AdventureWorks2012;
GO
WITH Parts(AssemblyID, ComponentID, PerAssemblyQty, EndDate, ComponentLevel) AS
(
    SELECT b.ProductAssemblyID, b.ComponentID, b.PerAssemblyQty,
        b.EndDate, 0 AS ComponentLevel
    FROM Production.BillOfMaterials AS b
    WHERE b.ProductAssemblyID = 800
          AND b.EndDate IS NULL
    UNION ALL
    SELECT bom.ProductAssemblyID, bom.ComponentID, p.PerAssemblyQty,
        bom.EndDate, ComponentLevel + 1
    FROM Production.BillOfMaterials AS bom 
        INNER JOIN Parts AS p
        ON bom.ProductAssemblyID = p.ComponentID
        AND bom.EndDate IS NULL
)
UPDATE Production.BillOfMaterials
SET PerAssemblyQty = c.PerAssemblyQty * 2
FROM Production.BillOfMaterials AS c
JOIN Parts AS d ON c.ProductAssemblyID = d.AssemblyID
WHERE d.ComponentLevel = 0; 

Open in new window


Kindly take a look over it and let me know in case you have any concern.

Best Regards,
Mohit Pandit
Avatar of 25112
25112

ASKER

thanks Mohit.. in your example, can you do INSERT, DELETE, UPDATE on Parts CTE?
ASKER CERTIFIED SOLUTION
Avatar of MohitPandit
MohitPandit
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 25112

ASKER

thank you Mohit