--创建测试表
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[实际销售表]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[实际销售表]
GO
CREATE TABLE [dbo].[实际销售表] (
[ID] [int] IDENTITY (1, 1) primary key NOT NULL ,
[销售月份] [nvarchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[订单号ID] [varchar] (30) COLLATE Chinese_PRC_CI_AS NULL ,
[销售单位ID] [nvarchar] (30) COLLATE Chinese_PRC_CI_AS NULL ,
[销售单位] [nvarchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[药品ID] [varchar] (4) COLLATE Chinese_PRC_CI_AS NULL ,
[药品名称] [nvarchar] (30) COLLATE Chinese_PRC_CI_AS NULL ,
[销售数量] [int] NOT NULL
) ON [PRIMARY]
GO
--创建触发器
create trigger tg_insert_销售表 on 实际销售表
instead of insert
as
declare @销售单位 nvarchar(20)
declare @药品ID nvarchar(20)
declare @药品名称 nvarchar(20)
declare @销售单位ID nvarchar(20)
declare @销售数量 int
declare @销售月份 varchar(10)
declare @订单号ID varchar(20)
declare @num int
declare test_cursor cursor for
select 销售月份,销售单位,销售单位ID,药品ID,药品名称,销售数量 from inserted
open test_cursor
fetch next from test_cursor into @销售月份,@销售单位,@销售单位ID,@药品ID,@药品名称,@销售数量
while @@fetch_status=0
begin
select @订单号ID=max(订单号ID) from 实际销售表 where 订单号ID like @销售月份 + '%'
if @订单号ID is null
set @订单号ID= @销售月份 + '-0000001'
else
begin
set @num=cast(substring(@订单号ID,10,7) as int)
set @num=@num + 1
if @num>=1000000
set @订单号ID=@销售月份 + '-' + cast(@num as varchar(7))
else if @num>=100000
set @订单号ID=@销售月份 + '-0' + cast(@num as varchar(6))
else if @num>=10000
set @订单号ID=@销售月份 + '-00' + cast(@num as varchar(5))
else if @num>=1000
set @订单号ID=@销售月份 + '-000' + cast(@num as varchar(4))
else if @num>=100
set @订单号ID=@销售月份 + '-0000' + cast(@num as varchar(3))
else if @num>=10
set @订单号ID=@销售月份 + '-00000' + cast(@num as varchar(2))
else if @num<10
set @订单号ID=@销售月份 + '-000000' + cast(@num as varchar(1))
end
insert into 实际销售表 values(@销售月份,@订单号ID,@销售单位ID,@销售单位,@药品ID,@药品名称,@销售数量)
if @@error<>0
begin
rollback tran
close test_cursor
deallocate test_cursor
return
end
fetch next from test_cursor into @销售月份,@销售单位,@销售单位ID,@药品ID,@药品名称,@销售数量
end
close test_cursor
deallocate test_cursor
--drop trigger tg_insert_销售表
--测试数据 单个数据的插入测试
insert into 实际销售表(销售月份,销售单位ID,销售单位,药品ID,药品名称,销售数量) values('20071103','','测试单位','0001','独24','9')
--select * from 实际销售表