将FB的触发器转换为MSSQL

时间:2017-04-25 12:40:45

标签: sql sql-server firebird

我需要你的帮助。我使用Firebird数据库的触发器。现在我已经改为MSSQL 2014数据库了。 我有一个触发器,我无法转换它。请给我你的帮助。我需要以下触发器才能在MSSQL中工作

CREATE TRIGGER AUTOGENEHMIGEN_BU FOR DATEPARAMS 
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE dutyuid integer;

BEGIN 
if (new.PARAMUID in (2,25) and new.AVALUE > CURRENT_DATE-7) then
begin
    select uid from duties where uid=new.DUTYUID 
    into :dutyuid;
    if(dutyuid>0) then 
        update duties set status='R' where uid=:dutyuid;
end
END

感谢您的努力

1 个答案:

答案 0 :(得分:1)

您需要注意很多事情。 MSSQL不支持触发器或逐行触发器(因此您不能使用新的。或旧的。构造) 并且您必须使用游标来逐行触发模拟。

为了让您在这里开始更新触发器,我将新旧值写入错误表中。

USE [Sandbox]
GO

/****** Object:  Table [dbo].[users]    Script Date: 25/04/2017 16:01:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[users](
    [user_id] [int] NULL,
    [contact_type_id] [int] NULL,
    [value] [varchar](20) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

user_id     contact_type_id value
----------- --------------- --------------------
1           2               aaa
1           3               aaa
2           1               example@mail.com
3           1               example2@mail.com
3           2               123345
3           3               skypeLogin2

(6 row(s) affected)

--drop trigger tai_users
CREATE TRIGGER TAI_users
on users 
after update 
AS

BEGIN 
 declare old cursor for select  value from deleted
 declare new cursor for select  value from inserted
 declare @oldvalue as varchar(20)
 declare @newvalue as varchar(20)

 open old
 open new
 fetch next from old into @oldvalue
 fetch next from new into @newvalue
  insert into errors (msg) values (concat(@oldvalue,',',@newvalue))
WHILE @@FETCH_STATUS = 0   
BEGIN   
       FETCH NEXT FROM old INTO @oldvalue 
       fetch next from new into @newvalue
       insert into errors (msg) values (concat(@oldvalue,',',@newvalue))
END   
  close old
  close new
  deallocate old
  deallocate new
END

--truncate table errors
update users 
    set value = 'bbb'
    where user_id = 1

select * from errors
select * from users

2           aaa,bbb
3           aaa,bbb
4           aaa,bbb

(4 row(s) affected)

user_id     contact_type_id value
----------- --------------- --------------------
1           2               bbb
1           3               bbb
2           1               example@mail.com
3           1               example2@mail.com
3           2               123345
3           3               skypeLogin2