tags:

views:

452

answers:

2

Hi

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

Id | Name | DefaultImageId

And one with Images:

Id | ProductId | Bytes

I want to run an Update statement, that updates the DefaultImageId on all records in the Products table with a random Id from the Images table that is related to the Product via the ProductId column.

Can anyone help out? Should be simple for any SQL Champ (Which is obviously not me)..

+1  A: 

Check this out.

Update Products
Set DefaultImageId = (
SELECT top 1 Id 
From Images 
Where 1=1
and Products.Id = Images.ProductId
ORDER BY NEWID()
)
Raj More
Msg 147, Level 15, State 1, Line 2An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
MartinHN
my apologies i corrected it.
Raj More
+2  A: 

You can do an order by on a NEWID to get a random number for every row of your update.

UPDATE
 Products
SET
 DefaultImageId =
 (
  SELECT TOP 1
   Id
  FROM
   Images
  WHERE
   Images.ProductId = Products.Id
  ORDER BY
   NEWID()
 )
Robin Day