Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL for Updating Rows with same value in a column

I have a table lets say called FavoriteFruits that has NAME, FRUIT, and GUID for columns. The table is already populated with names and fruits. So lets say:

NAME      FRUIT       GUID
John      Apple       NULL
John      Orange      NULL
John      Grapes      NULL
Peter     Canteloupe  NULL
Peter     Grapefruit  NULL

Ok, now I want to update the GUID column with a new GUID (using NEWID()), but I want to have the same GUID per distinct name. So I want all the John Smiths to have the same GUID, and I want both the Peters to have the same GUID, but that GUID different than the one used for the Johns. So now it would look something like this:

NAME      FRUIT       GUID
John      Apple       f6172268-78b7-4c2b-8cd7-7a5ca20f6a01
John      Orange      f6172268-78b7-4c2b-8cd7-7a5ca20f6a01
John      Grapes      f6172268-78b7-4c2b-8cd7-7a5ca20f6a01
Peter     Canteloupe  e3b1851c-1927-491a-803e-6b3bce9bf223
Peter     Grapefruit  e3b1851c-1927-491a-803e-6b3bce9bf223

Can I do that in an update statement without having to use a cursor? If so can you please give an example?

Thanks guys...

like image 791
Ryan Avatar asked Oct 24 '11 03:10

Ryan


1 Answers

Update a CTE won't work because it'll evaluate per row. A table variable would work:

You should be able to use a table variable as a source from which to update the data. This is untested, but it'll look something like:

DECLARE @n TABLE (Name varchar(10), Guid uniqueidentifier);

INSERT @n
SELECT Name, newid() AS Guid
FROM FavoriteFruits
GROUP BY Name;

UPDATE f
    SET f.Guid = n.Guid
FROM @n n
    JOIN FavoriteFruits f ON f.Name = n.Name

So that populates a variable with a GUID per name, then joins it back to the original table and updates accordingly.

like image 159
Matt Hamilton Avatar answered Sep 27 '22 23:09

Matt Hamilton