Skip to content
Advertisement

Have multiple parameters in a WHEN part of a SQL Update Statement

I need to write a sql update statement without repeating the parameter on the WHEN part of the query, below query works fine however I would like to group the related parameters together, this is how the current query looks like

UPDATE [dbo].[VIPCO_UserSTCRelation]
   SET [UserAccessId] = CASE [STC_Code]
    WHEN '841900' THEN 21
    WHEN '841300' THEN 9
    WHEN '841400' THEN 21
    WHEN '841305' THEN 21
    WHEN '846000' THEN 38
    WHEN '841002' THEN 38
    WHEN '841000' THEN 40
    WHEN '841005' THEN 40
    WHEN '841004' THEN 40
    END

for example I would like to use an IN to group bundle all the STCs belong to 40 together, I have tried the below part, but no joy

WHEN IN ('841000','841005','841004') THEN 40

Advertisement

Answer

You can move the conditions from the case to the when part of the expression:

UPDATE [dbo].[VIPCO_UserSTCRelation]
SET [UserAccessId] = CASE 
    WHEN [STC_Code] = '841300' THEN 9
    WHEN [STC_Code] IN ('841900', '841400', '841305') THEN 21
    WHEN [STC_Code] IN ('846000', '841002') THEN 38
    WHEN [STC_Code] IN ('841000', '841005', '841004') THEN 40
END
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement