Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL: Update values by using With statement?

I have a table with a column I would like to update its values. Here is an example of TSQL codes:

WITH Pieces(id, newdesc) AS
(
SELECT itemid, REPLACE(REPLACE(description, 'DESC_A', 'DESC_B'), 'NEW_1', 'NEW_2')
  FROM myTable
  WHERE description like '%DESC_A%DESC_B%'
)
-- SELECT * FROM Pieces
UPDATE myTable SET description = newdesc // not working, how?

This update is NOT working. By commenting out SELECT, I can see the result is what I need. How I can do this change in a batch way for a group of rows? Not sure is it possible by WITH statement?

Here are some example data:

....
xxxDESC_AyyyDESC_Bwwww
aaaDESC_AxxDESC_Beee
....

the udpated ones will be:

....
xxxNEW_1yyyNEW_2wwww
aaaNEW_1xxNEW_2eee
....
like image 713
David.Chu.ca Avatar asked Oct 19 '25 03:10

David.Chu.ca


2 Answers

maybe

UPDATE myTable 
SET description = newdesc
FROM Pieces
WHERE Pieces.id = myTable.itemid
like image 102
Jhonny D. Cano -Leftware- Avatar answered Oct 21 '25 17:10

Jhonny D. Cano -Leftware-


By the way, if you really want to use a CTE for the Update (although I prefer more straightforward updates), you can. But, you have to include the updated column in the CTE and the table you're updating is the CTE name, not the original tablename. Like this:

;WITH Pieces(id, description, newdesc) 
AS(
SELECT itemid, description, REPLACE(REPLACE(description, 'DESC_A', 'DESC_B'), 'NEW_1', 'NEW_2')  
FROM myTable  WHERE description like '%DESC_A%DESC_B%'
)
UPDATE Pieces SET description = newdesc 
like image 25
GilM Avatar answered Oct 21 '25 17:10

GilM