嗯,不知道这样的标题对不对,我是指这样的东西,一个数据表:
t_user_dept (udid int<pk>, uid int, deptid int)
然后呢,我要对uid=1的所有记录,查询对比,就是说啊,我现在的表里有这样的数据
udid | uid | deptid |
1 | 1 | 1 |
2 | 1 | 2 |
3 | 1 | 3 |
4 | 1 | 4 |
所以,deptid的所有组合字符串是这个:1,2,3,4,
如果现在我要输入一个deptid的组合字符串是“1,3,4,5,”,那我就要把uid=1 and deptid=2的记录删除,再加上一个uid=1, deptid=5的记录
我是这样做的:
create procedure a_user_dept_edit ( @uid int, @deptidStr varchar(300) ) as
declare @index int, @id int
if @deptidStr is null
begin
select @deptidStr=''
end
create table #temp ( did int )
if @deptidStr<>''
begin
if left(@deptidStr,1)=','
begin
select @deptidStr=substring(@deptidStr,2,len(@deptidStr) - 1)
end
if right(@deptidStr,1)<>','
begin
select @deptidStr=@deptidStr + ','
end
select @index=charindex(',', @deptidStr)
while @index>1
begin
select @id=substring(@deptidStr, 1, @index - 1)
if @id<>0
begin
insert into #temp (did) values (@id)
if not exists (select udid from T_user_dept where uid=@uid and deptid=@id)
begin
insert into T_user_dept (uid, deptid) values (@uid, @id)
end
end
select @deptidStr=substring(@deptidStr, @index + 1, len(@deptidStr) - @index)
select @index=charindex(',', @deptidStr)
end
end
delete from T_user_dept where uid=@uid and deptid not in (select did from #temp)