Update SQL table with random value from other table

后端 未结 6 1819
挽巷
挽巷 2020-12-31 06:56

On Microsoft SQL Server 2008, I have a table with Products:

Id | Name | DefaultImageId

And one with Images:

Id | ProductId |

6条回答
  •  一生所求
    2020-12-31 07:39

    Addressing @philreed's issue with the selected answer:

    Is there a way to assign each row being updated with a different value randomly chosen from the source table?

    UPDATE Products
    SET DefaultImageId = t2.Id
    FROM Products t1
    CROSS APPLY (
        SELECT TOP 1 Id
        FROM Images
        WHERE t1.Id = t1.Id
        ORDER BY newid()
        ) t2    
    

提交回复
热议问题