且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sql server触发器帮助-相同表更新

更新时间:2022-11-25 07:57:03

 创建触发器[dbo]。[test] on [dbo]。[发票] 
用于插入
,因为
开始

更新发票
set Trader_Status ='OPEN'
其中Invoice_Id在(从插入的位置选择Invoice_Id Invoice_Status ='PENDING')

更新Invoice
set Trader_Status ='BLOCKED'
其中Invoice_Id在(从插入的Invoice_Id中选择Invoice_Id = Invoice_Status ='OVERDUE')

end

请注意,这将处理单个语句插入的多个行。 / p>

I posted a similar question earlier - but can't seem to get a long enough response! Sorry if I shouldn't be posting again!

This is using SQL Server 2008. I have a table called invoice;

create table INVOICE(
INVOICE_ID numeric(5) PRIMARY KEY IDENTITY,
INVOICE_STATUS varchar(25) not null,
TRADER_STATUS varchar (25))

I want to create a trigger when an insert is entered; and the invoice_status = 'pending' - the trader_status is updated (triggered) to 'open'. When an insert is entered; and the invoice_status = 'overdue' - the trader_status is updated (triggered) to 'blocked'.

The trigger code I have;

CREATE TRIGGER [dbo].[test] on [dbo].[invoice]
FOR INSERT, UPDATE
AS 
BEGIN

SET NOCOUNT ON;
declare @invoice_status varchar(25)
select @invoice_status = (select invoice_status from  inserted WHERE invoice_status = 'PENDING')
insert into invoice (trader_status) values ('OPEN')

select @invoice_status = (select invoice_status from  inserted WHERE invoice_status = 'OVERDUE')
insert into invoice (trader_status) values ('BLOCKED')

 END
 GO

Any help is greatly appreciated!

create trigger [dbo].[test] on [dbo].[invoice]
for insert
as
begin

update Invoice
  set Trader_Status = 'OPEN'
  where Invoice_Id in ( select Invoice_Id from inserted where Invoice_Status = 'PENDING' )

update Invoice
  set Trader_Status = 'BLOCKED'
  where Invoice_Id in ( select Invoice_Id from inserted where Invoice_Status = 'OVERDUE' )

end

Note that this will handle more than one row being inserted by a single statement.