ITPUB论坛 » MS SQL Server » 求助 触发器
新一届的微软MVP评选已经开始,欢迎各位推荐!
2008-7-3 11:25 JJooO
求助 触发器

Create table product
(
pId char(6) primary key,
pName varchar(300) not null,
pPrice smallmoney,
pNum float
)
go


Create table sale
(
sNo int identity(1001,1) primary key,
sId char(6),
sPrice smallmoney,
sDate datetime
)
go

用触发器实现:
update product set pNum=pNum-x where pid=a

当这个发生的时候,sale表中插入数据,插入的行数 为 x(假设x为整数)
当x为float时候(比如x=5.5),插入的行数为6行。

如何实现。。。

2008-7-3 11:58 smthgdin
你可以自学一下~~~

2008-7-3 15:27 javens
這個應該很簡單,在UPDATE時候觸發即可

2008-7-3 17:27 JJooO
回复 #2 smthgdin 的帖子

呵呵

2008-7-3 17:34 sqysl
对,可以自学。

2008-7-3 23:39 cosio
[i][color=Blue]create trigger tri_test
as
declare @num int
select count(*) into @num from inserted
IF @num>0
    update product set pNum=pNum-@num where pid=a[/color][/i]
很久没有用SQL,忘记了不少,LZ可以自己学学!

2008-7-5 09:30 Ryan-liumin
呵呵  都要LZ自学啊

2008-7-8 20:17 xiebinren
自学

2008-7-9 11:15 沙漠孤鹰
回复 #1 JJooO 的帖子

这样理解楼主的意思,不晓得对不对?

写一个product表上的触发器
当修改表product的条件满足:update product set pNum=pNum-x where pid=a
就往sale表中写数据,写入数据的条数由 x 决定

Create Trigger TU_product on product
For Update
AS

declare @i_pId char(6), @i_pNnme varchar(300), @i_pPrice smallmoney, @i_pNum float
declare @d_pId char(6), @d_pNnme varchar(300), @d_pPrice smallmoney, @d_pNum float
declare @ftch_ins int, @ftch_del int
declare @x int, @i int

begin

  declare c_product_ins cursor for select pId, pName, pPrice, pNum from inserted
  open c_product_ins
  fetch c_product_ins into @i_pId, @i_pNnme, @i_pPrice, @i_pNum
  set @ftch_ins=@@fetch_status

  declare c_product_del cursor for select pId, pName, pPrice, pNum from deleted
  open c_product_del
  fetch c_product_del into @d_pId, @d_pNnme, @d_pPrice, @d_pNum
  set @ftch_del=@@fetch_status

  while (@ftch_ins+@ftch_del=0)
    begin
      if (@i_pId=@d_pId) and (@i_pId=a) and (@d_pNum>@i_pNum)
         and (@i_pNnme=@d_pNnme) and (@i_pPrice=@d_pPrice)  
        begin
          set @x=ceiling(@d_pNum-@i_pNum)

          set @i=1
          while @i<=@x
          begin
            insert into sale values(...)
            set @i=@i+1
          end
        end
      
      fetch c_product_ins into @i_pId, @i_pNnme, @i_pPrice, @i_pNum
      set @ftch_ins=@@fetch_status

      fetch c_product_del into @d_pId, @d_pNnme, @d_pPrice, @d_pNum
      set @ftch_del=@@fetch_status
    end

  close c_product_ins
  deallocate c_product_ins

  close c_product_del
  deallocate c_product_del

end

页: [1]
查看完整版本: 求助 触发器


Powered by ITPUB论坛