有个表 sendfile
有如下字段
docid,userid,title
22 ,7;8 ,关于春节放假通知
29 , 33 ,关于王平的处罚通告要求:
当往表 sendfile 里插入数据 或者更新 数据的时候, 要把 里面的3个字段的 数据写入 sendfile_full表中sid,docid,userid,title 其中 SID为自增长.注意: userid 里面 的 userid 可能存储2个或者2个以上的用户ID,用;割开这就意味着, 当我往 sendfile里插入 22, 7;8 ,关于春节放假通知这样的数据,那么 在 sendfile_full表中 就应该写入2条记录:sid,docid,userid,title
2 , 22 , 7 ,关于春节放假通知
3 , 22 , 8 ,关于春节放假通知请求支援 , 周日前立马结帐.
有如下字段
docid,userid,title
22 ,7;8 ,关于春节放假通知
29 , 33 ,关于王平的处罚通告要求:
当往表 sendfile 里插入数据 或者更新 数据的时候, 要把 里面的3个字段的 数据写入 sendfile_full表中sid,docid,userid,title 其中 SID为自增长.注意: userid 里面 的 userid 可能存储2个或者2个以上的用户ID,用;割开这就意味着, 当我往 sendfile里插入 22, 7;8 ,关于春节放假通知这样的数据,那么 在 sendfile_full表中 就应该写入2条记录:sid,docid,userid,title
2 , 22 , 7 ,关于春节放假通知
3 , 22 , 8 ,关于春节放假通知请求支援 , 周日前立马结帐.
create table tab
(
docid int,
userid varchar(50),
title varchar(100)
)create table sendfile_full
(
sid int identity(1,1),
docid int,
userid varchar(50),
title varchar(100)
)--建立辅助表
SELECT TOP 8000 id = identity(int,1,1)
INTO num FROM syscolumns a, syscolumns b --建立触发器
create trigger t_tab on tab
for update,insert
as
begin
if exists (select 1 from deleted)
begin
delete from sendfile_full where docid in (select docid from deleted)
end
insert into sendfile_full(docid,userid,title)
SELECT A.docid,userid = SUBSTRING(A.userid, B.ID, CHARINDEX(';', A.userid + ';', B.ID) - B.ID),title
FROM inserted A, num B
WHERE SUBSTRING(';' + a.userid, B.id, 1) = ';' end--插入数据
insert into tab select 22 ,'7;8' ,'关于春节放假通知'
--查询
select * from sendfile_full
1 22 7 关于春节放假通知
2 22 8 关于春节放假通知
--更新数据
update tab set userid = '33'
--查询
select * from sendfile_full
3 22 33 关于春节放假通知 --删除环境
drop table tab
drop table sendfile_full
create table tb(r_id int identity(1,1),docid int,userid varchar(50),title varchar(20))--truncate table ta
select * from ta
select * from tbcreate trigger test_tr on ta
for insert,update--定义插入、更新都触发
as
begin
DECLARE @docid int,@userid varchar(50),@title varchar(20)
DECLARE roy CURSOR
FOR SELECT * from inserted
OPEN roy
FETCH next FROM roy
into @docid,@userid,@title
WHILE @@FETCH_STATUS = 0
BEGIN
begin
while CHARINDEX(';',@userid)>0
begin
INSERT tb select @docid,LEFT(@userid,CHARINDEX(';',@userid)-1) ,@title
SET @userid=STUFF(@userid,1,CHARINDEX(';',@userid),'')
end
insert tb select @docid,@userid,@title
end
FETCH NEXT FROM roy
into @docid,@userid,@title
END
CLOSE roy
DEALLOCATE roy
end--测试
insert ta
select 22 ,'7;8' ,'关于春节放假通知' union all
select 29 , '33' ,'关于王平的处罚通告'
--查询
select * from tbr_id docid userid title
----------- ----------- -------------------------------------------------- --------------------
1 22 7 关于春节放假通知
2 22 8 关于春节放假通知
3 29 33 关于王平的处罚通告(所影响的行数为 3 行)
谢谢 2楼和3楼的支持