As I am sure many will note here in their answers, you do not have to use a Common Table Expression to accomplish this UPDATE.
That said, however, you could (in case you are looking to practice your CTE skills):
WITH cte AS
(
SELECT c1.compID, c2.name, c2.cpuSpeed
FROM [COMPUTER] AS c1
LEFT OUTER JOIN [CPU_TYPE] AS c2
ON ( comp.cpuId = c2.cpuId )
)
UPDATE [COMPUTER]
SET cpu = cte.name + ', ' + cte.cpuSpeed
FROM [COMPUTER] AS comp
INNER JOIN cte ON ( comp.compId = cte.compId )
If you wanted to filter your CTEs result then you could add a WHERE clause to your CTE like:
WHERE c1.cpuId IS NOT NULL
Or anything else for that matter.
Update
If you do, in fact, have NULL data in your cpuSpeed
column, then you may want to consider the following SET
statement instead of the SET
listed above:
SET cpu = cte.name + Coalesce(', ' + cte.cpuSpeed, '')
...or alternatively:
SET cpu = cte.name + IsNull(', ' + cte.cpuSpeed, '')
This way if cpuSpeed
is NULL, then you still have the data from the name
column without the comma (",") appended at the end; if name
is also NULL (or NULL instead is cpuSpeed
), then cpu
will be set to NULL.
Remember, you could always add an even more protective filter to your CTE, like:
WHERE c1.cpuId IS NOT NULL AND c2.name IS NOT NULL
Naturally, you should adjust the SQL to suit your specific requirements.
I hope this helps. Good luck!