循环遍历sql server触发器中的数据

时间:2013-04-11 10:02:56

标签: sql sql-server loops select triggers

我有一个sql-server触发器,它在开头做一个select。该选择返回数百行,我想循环这些行。如何循环返回的数据?

这是我的触发器,我想循环@ProfId

Create TRIGGER EmailQueueRaw_Control_Trigger ON EmailQueueRaw FOR INSERT
AS
BEGIN
   SELECT @ProfId= ProfessionalID,@Email= Email from Professionals 
END

如何循环@ProfId?

1 个答案:

答案 0 :(得分:4)

试试这个解决方案 -

ALTER TRIGGER [LabourAPI].[trg_IOIU_Employee]

   ON [LabourAPI].[Employee]
   INSTEAD OF INSERT, UPDATE

AS BEGIN

    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    DECLARE
          @EmployeeID INT
        , @PersonID INT
        , @TabelNumber VARCHAR(6)
        , @DepartmentUID UNIQUEIDENTIFIER
        , @PositionID INT
        , @DateIn DATETIME
        , @DateOut DATETIME
        , @IsMainWorkPlace BIT
        , @DatePension DATETIME
        , @IsLabourUnionMember BIT
        , @FiringReasonID INT

    DECLARE cur CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
    SELECT
          EmployeeID
        , PersonID
        , TabelNumber
        , DepartmentUID
        , PositionID
        , DateIn
        , DateOut
        , IsMainWorkPlace
        , DatePension
        , IsLabourUnionMember
        , FiringReasonID
    FROM INSERTED

    OPEN cur

    FETCH NEXT FROM cur INTO
          @EmployeeID
        , @PersonID
        , @TabelNumber
        , @DepartmentUID
        , @PositionID
        , @DateIn
        , @DateOut
        , @IsMainWorkPlace
        , @DatePension
        , @IsLabourUnionMember
        , @FiringReasonID

    WHILE @@FETCH_STATUS = 0 BEGIN

        SELECT
              @PersonID 
            , @TabelNumber 
            , @DepartmentUID 
            , @PositionID 
            , @DateIn 
            , @DateOut 
            , @IsMainWorkPlace 
            , @DatePension 
            , @IsLabourUnionMember 
            , @FiringReasonID

        FETCH NEXT FROM employee INTO
              @EmployeeID
            , @PersonID
            , @TabelNumber
            , @DepartmentUID
            , @PositionID
            , @DateIn
            , @DateOut
            , @IsMainWorkPlace
            , @DatePension
            , @IsLabourUnionMember
            , @FiringReasonID

    END

    CLOSE cur
    DEALLOCATE cur

END