日期:2014-05-18 浏览次数:20733 次
CREATE TABLE [dbo].[web_user]( [user_id] [bigint] IDENTITY(1,1) NOT NULL, [user_mail] [nvarchar](50) NULL, [user_name] [nvarchar](50) NULL, [user_type] [int] NULL, [user_money] [decimal](20, 2) NULL ) ON [PRIMARY] CREATE TABLE [dbo].[web_user_backup]( [user_id] [bigint] IDENTITY(1,1) NOT NULL, [user_mail] [nvarchar](50) NULL, [user_name] [nvarchar](50) NULL, [user_type] [int] NULL, [user_money] [decimal](20, 2) NULL ) ON [PRIMARY]
当然可以 1: create trigger t_insert_web_user on web_user for insert as if exists(select 1 from inserted where user_type = '1') begin update web_user set user_money = isnull(user_money,0) + 100 from inserted i where i.user_id = web_user.user_id and i.user_type = '1' end 2: create trigger t_insert_web_user on web_user for delete as insert into web_user_backup(user_id,user_mail,user_name,user_type,user_money) select user_id,user_mail,user_name,user_type,user_money from deleted 3: create trigger t_update_web_user on web_user for update as if update(user_money) and exists(select 1 from inserted ,deleted where inserted.user_money > 50000 and inserted.user_id = deleted.user_id and inserted.user_money <> deleted.user_money) begin update web_user set user_money = 50000 + 50000 / 100 from inserted ,deleted where inserted.user_id = web_user.user_id and insertedi.user_id = deleted.user_id and inserted.user_money <> deleted.user_money and insertedi.user_money > 50000 end
------解决方案--------------------
CREATE TABLE [dbo].[web_user](
[user_id] [bigint] IDENTITY(1,1) NOT NULL,
[user_mail] [nvarchar](50) NULL,
[user_name] [nvarchar](50) NULL,
[user_type] [int] NULL,
[user_money] [decimal](20, 2) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[web_user_backup](
[user_id] [bigint] IDENTITY(1,1) NOT NULL,
[user_mail] [nvarchar](50) NULL,
[user_name] [nvarchar](50) NULL,
[user_type] [int] NULL,
[user_money] [decimal](20, 2) NULL
) ON [PRIMARY]
具体实现:
当插入的时候,user_type为1时,user_money字段自动用原有的值加上100:
create trigger tri_insert1 on web_user
for insert
as
if exists(select 1 from inserted where user_type = '1')
begin
update web_user
set user_money = isnull(user_money,0) + 100
from inserted
where inserted .user_id = web_user.user_id
and inserted .user_type = '1'
end
当删除的时候,将删除记录备份到web_user_backup:
create trigger tri_insert2 on web_user
for delete
as
insert into web_user_backup(user_id,user_mail,user_name,user_type,user_money)
select user_id,user_mail,user_name,user_type,user_money from deleted
当更新的时候,如果user_money大于50000。user_money字段等于50000 + 50000 / 100:
create trigger tri_update on web_user
for update
as
if update(user_money) and exists(select 1 from inserted ,deleted
where inserted.user_money > 50000
and inserted.user_id = deleted.user_id
and inserted.user_money <> deleted.user_money)
begin
update web_user
set user_money = 50000 + 50000 / 100
from inserted ,deleted
where inserted.user_id = web_user.user_id
and insertedi.user_id = deleted.user_id
and inserted.user_money <> deleted.user_money
and insertedi.user_money > 50000
end