I have 3 columns that indicate if a company is active during the last 3 years (2021_active, 2020_active, 2019_active). I want to use a case statement to check if the company was active in 2020 or 2019, but is NOT active in 2021
ALTER Table [TMDB].[dbo].[2021 CCVL Draft] ADD Cancelled_CV varchar(10)
UPDATE [TMDB].[dbo].[2021 CCVL Draft]
SET Cancelled_CV = CASE WHEN [TMDB].[dbo].[2021 CCVL Draft].[2021_Active] = 'N' THEN
CASE [TMDB].[dbo].[2021 CCVL Draft].[2019_Active] WHEN 'Y' THEN 'Y' ELSE
CASE [TMDB].[dbo].[2021 CCVL Draft].[2020_Active] WHEN 'Y' THEN 'Y'
ELSE 'N' END
I'm getting an error for the last line of the code: Incorrect syntax near the keyword 'ELSE'.
The logic I want to implement is to first check to ensure 2021_active is N for No, and then, check if either 2019_active or 2020_active are yes.
You are nesting multiple CASE
expressions but do not have enough END
s. Nesting CASE
expressions is rarely needed. I'm not sure what the exact logic you want is, but something like this:
UPDATE [TMDB].[dbo].[2021 CCVL Draft]
SET Cancelled_CV = (CASE WHEN [TMDB].[dbo].[2021 CCVL Draft].[2021_Active] = 'N' AND
[TMDB].[dbo].[2021 CCVL Draft].[2019_Active] = 'Y'
THEN 'Y'
WHEN [TMDB].[dbo].[2021 CCVL Draft].[2020_Active] = 'Y'
THEN 'Y'
ELSE 'N'
END)
EDIT:
The logic I want to implement is to first check to ensure 2021_active is N for No, and then, check if either 2019_active or 2020_active are yes.
For this logic, I think you want:
UPDATE [TMDB].[dbo].[2021 CCVL Draft]
SET Cancelled_CV = (CASE WHEN [2021 CCVL Draft].[2021_Active] = 'N' AND
([2021 CCVL Draft].[2019_Active] = 'Y' OR
[2021 CCVL Draft].[2020_Active] = 'Y'
)
THEN 'Y'
ELSE 'N'
END)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.