Here you go. Basically, it checks to see if there are any Active records in that set, and if not, updates the first one (determined by the picID). You can stick it in a stored procedure or function if you like, or just run the script and change the gallery ID manually.
DECLARE @Count INT,
@GalleryID INT
SET @GalleryID = 3
SELECT @Count = COUNT(*)
FROM tblPictures
WHERE galleryID=@GalleryID and isActive=1
IF @Count = 0
BEGIN
UPDATE tblPictures
SET isActive = 1
WHERE picID = (
SELECT TOP 1 picID
FROM tblPictures
WHERE galleryID = @GalleryID
ORDER BY picID
)
END
MOAR CODE
This should update the first picture (by picID) in any gallery without an active picture:
UPDATE tblPictures
SET isActive = 1
WHERE picID IN (
SELECT picID
FROM (
SELECT galleryID, MIN(picID) AS 'picID'
FROM tblPictures AS p
JOIN (
SELECT galleryID
FROM tblPictures
WHERE isActive = 1
) AS s ON p.galleryID <> s.galleryID
GROUP BY galleryID
)
)
The innermost subquery finds the galleries that DO have active pictures. The next step up finds the galleryIDs excluding the ones that have pictures. Then we find the lowest picID for each galleryID and use those to update the table.
galleryID = 3
, which one of those five rows is "first"?