Sql-server – Subquery returned more than 1 value. This is not permitted + Trigger Error SQL Server

sql servertrigger

This trigger will update Is_Confidential_or_VIP column to 1 or 0 based on the text inserted or updated into ConfidentialRegistrationFlag and VIPType columns :

create trigger [dbo].[Is_Confidential_or_VIP]
on  [EDB].[dbo].[Patient_Info]
after update,insert 
AS
BEGIN
    declare @type1 nvarchar(max)
    declare @type2 nvarchar(max)

    (select @type1 = ConfidentialRegistrationFlag from inserted)
    (select  @type2 = VIPType from inserted)

    declare @flag int

    if (@type2 like 'MDP-A' or @type2 like 'MDP-B' or @type1= 'confidential')
       set @flag= 1
    else 
       set @flag= 0

    update EDB.dbo.Patient_Info
    set Is_Confidential_or_VIP = @flag
    where EPN = (select EPN from inserted)
 END

I have a problem when enabling this trigger cannot insert data and error msg:

Subquery returned more than 1 value

Best Answer

Actually Triggers fire once rather than multiple times if update statement modify more than one row.

Your trigger trying to update multiple rows which means Inserted table will also have more than one row and when you try to set Flag values, it return you error.

Join your table's key with Inserted

CREATE TRIGGER [dbo].[Is_Confidential_or_VIP] ON [EDB].[dbo].[Patient_Info]
    AFTER UPDATE, INSERT
AS
    BEGIN

        UPDATE  patinfo
        SET     Is_Confidential_or_VIP = CASE WHEN VIPType = 'MDP-A'  --- 'Like' Replaced with '='
                                                   OR VIPType = 'MDP-B'
                                                   OR ConfidentialRegistrationFlag = 'confidential'
                                              THEN 1
                                              ELSE 0
                                         END                    
         -- select case VIPType = 'MDP-A' OR VIPType = 'MDP-B'  OR ConfidentialRegistrationFlag = 'confidential' then 1 else 1  END,*
        FROM    EDB.dbo.Patient_Info patinfo
                INNER JOIN inserted i ON patinfo.EPN = i.EPN

    END