我想知道如何将Oracle触发器转换为SQL Server触发器

时间:2016-04-12 06:46:04

标签: sql-server oracle

据我所知,SQL SERVER触发器不支持FOR EACH ROW。另外我知道你必须使用插入表和删除表。除此之外,我不知道如何编写SQL Server触发器。他们看起来如此不同。请问有些帮助吗?

以下是Oracle触发器的代码

create or replace TRIGGER Ten_Percent_Discount   
BEFORE INSERT OR UPDATE ON Bookings  
FOR EACH ROW
DECLARE CURSOR C_Passengers IS 
SELECT StatusName
FROM   Passengers
WHERE  PassengerNumber = :NEW.Passengers_PassengerNumber;
l_status_name Passengers.StatusName%TYPE;
BEGIN 
OPEN  C_Passengers;
FETCH C_Passengers INTO l_status_name;
CLOSE C_Passengers;

以下是我到目前为止所写的内容。我知道我使用插入的表错了

IF l_status_name = 'Regular' 
THEN 
 :New.TotalCost := 0.90 * :New.TotalCost;
END IF;
END;

create TRIGGER Ten_Percent_Discount  
ON Customer
FOR INSERT ,UPDATE  
AS 
DECLARE  C_Passengers CURSOR FOR
SELECT StatusLevel
FROM   Customer
WHERE  CustomerID = inserted.CustomerID

提前感谢所有帮助。

客户的表格结构

Table structure for Customer

订单的表结构

Table structure for Order

1 个答案:

答案 0 :(得分:0)

以下答案仅供参考,您可以逐步建立最终解决方案:

create table dbo.customer
(
customerid varchar(10),
firstname nvarchar(50),
statuslevel varchar(50)
)
go
create table dbo.customerorder
(
orderid varchar(10),
totalprice numeric(5,2),
productid varchar(10),
customerid varchar(10)
)
go
go
create trigger dbo.tr_customer on dbo.customer for insert,update
as
begin
    update co
    set co.totalprice = .9*co.totalprice
    from dbo.customerorder co
    inner join inserted i
    on co.customerid = i.customerid
    where i.statuslevel = 'Standard' 
end
go

--test for above code
insert into dbo.customer values (1,'jayesh','')
insert into dbo.customerorder values (1,500.25,1,1)
insert into dbo.customerorder values (1,600.25,2,1)
select * from dbo.customer
select * from dbo.customerorder

update dbo.customer set statuslevel = 'Standard' where customerid = 1

select * from dbo.customer
select * from dbo.customerorder

但我非常确定的是,当客户第一次创建时,将不会有任何订单来应用折扣,因此您肯定也需要UPDATE Trigger。