3

我有一个包含以下行的表。

tbl图片

  • PICID
  • 图片名称
  • 画廊ID
  • 活跃

我想运行一个查询来选择例如所有带有galleryID=3和的图片isActive=1

如果此选择中没有图片且 isActive 行为 1(换句话说,查询不返回任何结果)我想isActive=1galleryID=3

有人可以指导我吗?

4

2 回答 2

5

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.

于 2012-09-13T22:58:20.043 回答
-1

尝试这个:

declare @tav table

(

gallaryid int,

isactive int

)

insert into @tav 

select

3,0 union all

select

4,0 union all

select

5,1

select * from @tav

update @tav set isactive=1

where gallaryid=3 and isactive=(select top(1)isactive from @tav  order by isactive)

select * from @tav

where gallaryid=3 and isactive=1
于 2012-09-14T07:19:20.977 回答