我有ArticlePhotos表,每篇文章都可以有N张照片。我正在编写一个触发器,它将反映在ArticlePhotos表中所做的更改,以在Article表中创建一个平面的hierarhy,以便在列出多篇文章时更快地查询以避免连接。
有没有办法在某种CASE子句中选择要更新的列,而是为每种所需类型编写update子句
DECLARE @FrontPagePhotoTypeId INT = 1;
DECLARE @MainArticlePhotoTypeId INT = 2;
DECLARE @FacebookPhotoType INT = 4;
-- all deleted photo records should be set as null in Articles table (flat hierarchy)
-- delete frontpage photo
UPDATE Articles
SET Articles.FrontPagePhoto = NULL <-- can this be written as a case by PhotoTypeId
FROM Articles
INNER JOIN deleted
ON Articles.id = deleted.ArticleId WHERE deleted.PhotoTypeId = @FrontPagePhotoTypeId
-- delete Main Article Photo
UPDATE Articles
SET Articles.MainArticlePhoto = NULL
FROM Articles
INNER JOIN deleted
ON Articles.id = deleted.ArticleId WHERE deleted.PhotoTypeId = @MainArticlePhotoTypeId
-- delete facebook
UPDATE Articles
SET Articles.FacebookPhoto = NULL
FROM Articles
INNER JOIN deleted
ON Articles.id = deleted.ArticleId WHERE deleted.PhotoTypeId = @FacebookPhotoType
答案 0 :(得分:2)
上述查询可以重写为单个更新,如下所示
DECLARE @FrontPagePhotoTypeId INT = 1;
DECLARE @MainArticlePhotoTypeId INT = 2;
DECLARE @FacebookPhotoType INT = 4;
UPDATE Articles
SET
FrontPagePhoto = case when deleted.PhotoTypeId = @FrontPagePhotoTypeId
then null
else Articles.FrontPagePhoto end,
MainArticlePhoto = case when deleted.PhotoTypeId = @MainArticlePhotoTypeId
then null
else Articles.MainArticlePhoto end,
FacebookPhoto = case when deleted.PhotoTypeId = @FacebookPhotoType
then null
else Articles.FacebookPhoto end
FROM Articles
INNER JOIN deleted
ON Articles.id = deleted.ArticleId