IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_pms_user_order]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_pms_user_order]
GO
CREATE procedure [dbo].[mps_save_pms_user_order](
@cmpid int,
@objtype varchar(20),
@ctgid int,
@objid bigint,
@ptype varchar(20),
@cuids varchar(max) 
) as
begin 
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
create table #t (cuid int) 
declare @i int,@curInd int,@strlen int,@tmps varchar(100) ,@srcs varchar(max)
set @srcs = @cuids 
select @curInd=1,@strlen=LEN(@srcs) 
while (@curInd<=@strlen) 
begin 
select @i=charindex(',',@srcs,@curInd) 
if (@i>0) 
begin 
select @tmps=SUBSTRING(@srcs,@curInd,@i-@curInd) 
set @curInd=@i+1 
end else if (@curInd<=@strlen) 
begin 
select @tmps=SUBSTRING(@srcs,@curInd,@strlen-@curInd+1) 
set @curInd=@strlen+1 
end 
if (@tmps>'') insert into #t(cuid) values(convert(bigint,@tmps)) 
end
declare @ptype2 varchar(20) 
set @ptype2 = @ptype 
if (charindex('my',@ptype)=1) set @ptype2 = substring(@ptype , 3,30) 

declare @tbname varchar(50)
declare @dbname varchar(50)
declare @fkey   varchar(50) 
exec sys_sql_getTableNamePk @cmpid,@objtype,@ctgid,0,@tbname output,@fkey output ,@dbname output 


declare @sql nvarchar(4000) 
set @sql = N'
delete '+@dbname+@tbname+'_users where ordp_type='''+@ptype2+''' and ordp_ordid='+convert(varchar(10),@objid) +' and ordp_otid=-2 
insert into '+@dbname+@tbname+'_users(ordp_type,ordp_ordid,ordp_cuid,ordp_otid) 
select '''+@ptype2+''' , '+convert(varchar(10),@objid)+',cuid,-2 from #t 
where not exists (select 1 from '+@dbname+@tbname+'_users where 
ordp_type='''+@ptype2+''' and ordp_ordid='+convert(varchar(10),@objid)+' and ordp_cuid=cuid) 
delete '+@dbname+@tbname+'_users where ordp_type='''+@ptype+''' and ordp_ordid='+convert(varchar(10),@objid) +' 
insert into '+@dbname+@tbname+'_users(ordp_type,ordp_ordid,ordp_cuid,ordp_otid) 
select '''+@ptype+''' , '+convert(varchar(10),@objid)+',cuid,-2  from #t ' 

exec sp_executesql @sql

drop table #t 
end