Update SQL table with random value from other table

后端 未结 6 1815
挽巷
挽巷 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:50

    Try this one (on AdventureWorks):

    It updates all rows of the person table with a new random name from the product table.

    begin tran
    --show initial state:
    select top 25 * from person.person order by BusinessEntityID
    
    update person.person
    set 
    FirstName = otherTable.Name
    from 
    (select BusinessEntityID, row_number() over (order by newid()) as row_num from person.person) p2
    ,(select ProductId, Name, row_number() over (order by newid()) as row_num from production.product) as otherTable
    where 
    person.person.BusinessEntityID=p2.BusinessEntityID 
    and (p2.row_num%500)=(otherTable.row_num%500) -- deal with tables with different rowcount
    
    --check results:
    select top 25 * from person.person order by BusinessEntityID
    
    rollback tran
    

    Or try a similar query on SQL Fiddle: http://sqlfiddle.com/#!3/8b719/1

提交回复
热议问题