循环遍历sql server trigger中的数据

Posted

技术标签:

【中文标题】循环遍历sql server trigger中的数据【英文标题】:loop through data in sql server trigger 【发布时间】:2013-04-11 10:02:55 【问题描述】:

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

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

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

如何循环@ProfId?

【问题讨论】:

【参考方案1】:

试试这个解决方案 -

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

【讨论】:

以上是关于循环遍历sql server trigger中的数据的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 2008 中的 While 循环遍历日期范围,然后插入

动态 SQL Server 查询循环遍历架构查找主键重复

SQL server中遍历所有行的循环表达式怎么写

SQL SERVER循环遍历(普通循环和游标循环)

SQL Server:循环遍历每个(PARTITION BY ...)元素的过程或函数

SQL Server 每 5 行循环遍历一个表