我有一个包含以下行的表。
tblPictures
我想运行一个查询,例如选择galleryID=3
和isActive=1
如果此选择中没有图片且isActive行为1(换句话说,查询不返回任何结果)我想用isActive=1
galleryID=3
有人可以指导我吗?
答案 0 :(得分:4)
你走了。基本上,它检查该集合中是否有任何活动记录,如果没有,则更新第一个(由picID确定)。如果您愿意,可以将其粘贴到存储过程或函数中,或者只是运行脚本并手动更改库ID。
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
这应该在没有活动图片的任何图库中更新第一张图片(通过picID):
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
)
)
最里面的子查询找到有活动图片的图库。下一步找到galleryIDs,不包括有图片的那些。然后我们找到每个galleryID的最低picID,并使用它们更新表格。
答案 1 :(得分:-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