用触发器完成多条数据添加

user表有字段
user_id not null
username not null
userped not null

friend表有字段
user_id not null
friend_id not null
f_address not null (对应person表)
f_birthday not null (对应person表) 

person表有字段
user_id not null
birthday not null(数据随便添加)
address not null(数据随便添加)

需求
当我向user表中添加一条数据的时候,向person表中添加一条数据,在Friend表中将用户加为所有人的好友,
在把所有人添加为该用户的好友(用触发器完成)

作者: kaimzge   发布时间: 2011-06-13

SQL code
create trigger tr_user_insert
on user
for insert
as

-- 向person表中添加一条数据
insert person(
user_id ,
birthday ,  --(数据随便添加)
address     -- (数据随便添加)
)
select 
user_id ,
birthday = '2011-01-01',  --(数据随便添加)
address  =''   -- (数据随便添加)
from inserted

-- 在Friend表中将用户加为所有人的好友
insert friend(
user_id ,
friend_id ,
f_address , -- (对应person表)
f_birthday   -- (对应person表)  
)
select 
i.user_id ,
friend_id =p.user_id,
f_address =p.address, -- (对应person表)
f_birthday =p.birthday  -- (对应person表)  
from inserted i,person p
where i.user_id <> p.user_id

-- 在把所有人添加为该用户的好友
insert friend(
user_id ,
friend_id ,
f_address , -- (对应person表)
f_birthday   -- (对应person表)  
)
select 
p.user_id ,
friend_id =i.user_id,
f_address ='', -- (对应person表)
f_birthday ='2011-01-01'  -- (对应person表)  
from inserted i,person p
where i.user_id <> p.user_id

go

作者: CSDNDoc   发布时间: 2011-06-13

insert into ...select * from inserted

作者: fredrickhu   发布时间: 2011-06-13

引用 2 楼 fredrickhu 的回复:

insert into ...select * from inserted
insert into ...select * from inserted

作者: xuexiaodong2009   发布时间: 2011-06-13

比较讨厌用触发器的路过

作者: happyideal   发布时间: 2011-06-13