触发器中的光标无法按预期工作

时间:2016-08-08 05:31:47

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我在触发器中跟踪游标代码,每小时将5条记录移动到一个新的表中,游标可以独立工作,但在触发器中它不起作用。 TableA在每次加载之前都会被截断。

我的光标逻辑

    $path  = the exact path to the correct folder where the file is;
    $templ = the part of the filename I know for sure;
    $fileExt = the extension of the file (I know it);

    $file = $path . "/" . glob( "*" . $templ . $fileExt );

我的光标位于触发代码中:

  Declare @a[varchar](50),@b[varchar](50),@c[varchar](50),@d[varchar](50),@e[varchar](50)
-- declare a cursor
DECLARE insert_cursor CURSOR FOR 
SELECT [a]
      ,[b]
      ,[c]
      ,[d]
      ,[e]
       FROM TableA

-- open cursor and fetch first row into variables
OPEN insert_cursor
FETCH NEXT FROM insert_cursor into  @a,@b,@c,@d,@e

-- check for a new row
WHILE @@FETCH_STATUS=0
BEGIN
-- do complex operation here
Insert into TableB
SELECT  @a,@b,@c,@d,@e
-- get next available row into variables
FETCH NEXT FROM insert_cursor into  @a,@b,@c,@d,@e
END
close insert_cursor
Deallocate insert_cursor

任何人都可以指出我在哪里做错了吗?

1 个答案:

答案 0 :(得分:1)

您没有从TableA插入表中进行选择,这意味着您要将TableA的每个插入的TableA的所有表值插入TableB

您可以将触发器更改为setbased ..而不是代码插入意味着..

当TableA插入发生在表B中时...表A中没有插入。

将基于设置的代码更改为以下..

 CREATE TRIGGER IO_ABC_INSERT  ON TABLEA 
INSTEAD OF INSERT
AS
BEGIN

Insert into TableB
select a,b,c,d,e from Inserted

End