0

OK, the title is a mouthful.

Basically, it means that when dealing with rows from the inserted table, depending on a value in a specific column, which splits the rows into one of two subsets, the data get dealt with in one of two manners. Now this could have been iterated over with a cursor, likely CTE too, but is there another way, the following (pseudo) code looks UGLY and doesn't actually work, but it gives you an idea of what I'm looking for:

Trigger

ALTER trigger [dbo].[tcdA_Combined_ActiveUnitShiftExpiredStatus_UpdateShift] on [dbo].[cd_units] after update as
begin

SET NOCOUNT ON

IF UPDATE(shift_start) 
BEGIN

    IF(inserted.ag_id <> 'FIRE')
        BEGIN
            update cd_units set shift_expired_status = 0
            from inserted
            where inserted.unid = cd_units.unid and inserted.shift_start <= dbo.get_dts()
        END
    ELSE 
        BEGIN
            update cd_units set shift_expired_status = 0
            from inserted
            where inserted.unid = cd_units.unid and inserted.shift_start >= dbo.get_dts()
        END

        update cd_units set sask911_shift_end = (select substring(shift_start,5,2)+'/'+substring(shift_start,7,2)
        +' '+substring(shift_start,9,2)+':'+substring(shift_start,11,2) from inserted)
        from cd_units join inserted on cd_units.unid=inserted.unid;
    END
END

As always, thanks in advance for all the help

4

1 回答 1

2

I think the main problem here is that you are treating inserted as a single row, whereas all triggers in SQL Server are table level triggers. Thus, inserted is a table, and you can't compare a column to a single value. I would do it with something like the following.

This part is for both branches:

update cd_units set shift_expired_status = 0
from inserted
where inserted.unid = cd_units.unid
  and inserted.shift_start <= dbo.get_dts();

This part only updates when inserted.ag_id = 'FIRE':

update cd_units
set sask911_shift_end = substring(inserted.shift_start,5,2) + '/' +
                        substring(inserted.shift_start,7,2) + ' ' +
                        substring(inserted.shift_start,9,2) + ':' +
                        substring(inserted.shift_start,11,2)
from cd_units join inserted on cd_units.unid=inserted.unid
where inserted.ag_id = 'FIRE';
于 2013-08-13T03:43:52.150 回答