[英]SQL choose column to update inside CASE condition
I have ArticlePhotos table and each Article can have N photos. 我有ArticlePhotos表,每个Article可以有N张照片。 I am writing a trigger which will reflect changes made in ArticlePhotos table to create a flat hierarhy inside Articles table for faster querying to avoid joins when listing several articles. 我正在编写一个触发器,该触发器将反映ArticlePhotos表中所做的更改,以在Articles表中创建一个简单的层次结构,以便更快地进行查询以避免在列出几篇文章时出现联接。
Is there a way to select column to update in some sort of CASE clause instead writing update clause for each desired type 有没有一种方法可以选择要在某种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
The above query can be re-written as a single update as below 上面的查询可以重写为单个更新,如下所示
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.