IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_ord_relations]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_ord_relations]
GO
CREATE procedure [dbo].[mps_g_ord_relations](
@cmpid int,
@scrmid int,
@ordid bigint,
@rcrmid int,
@useruid int ,  
@pagesize int , 
@pagecount int , 
@pageobjids varchar(8000)
)
as 
begin
set nocount on  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
declare @stbname varchar(50)
declare @sdbname varchar(50)
declare @sfkey   varchar(50) 
exec sys_sql_getTableNamePk @cmpid,'biz',@scrmid,0,@stbname output,@sfkey output ,@sdbname output 

declare @rtbname varchar(50)
declare @rdbname varchar(50)
declare @rfkey   varchar(50) 
exec sys_sql_getTableNamePk @cmpid,'biz',@rcrmid,0,@rtbname output,@rfkey output ,@rdbname output 


declare @sql nvarchar(max) 
declare @amount int  
declare @s1 varchar(8000) 
declare @s2 varchar(100) 
declare @i int 
select @amount = @pagecount*@pagesize 
exec drop_temp_table '#pobjs' 
create table #pobjs(nid int identity(1, 1), ordid bigint) 
set @s1 = '' --@pageobjids  
while (@s1>'')  
begin 
  set @i = charindex(',', @s1) 
  if (@i>0) 
  begin 
    set @s2 = substring(@s1,1,@i-1) 
    set @s1 = substring(@s1,@i+1,len(@s1)-@i) 
  end else  
  begin 
    set @s2 = @s1 
    set @s1 = ''  
  end  
  insert into #pobjs(ordid) values(convert(bigint,@s2)) 
end 
if (exists (select top 1 * from #pobjs)) 
begin 
set @sql = 'select * from '+@rdbname+@rtbname+' a , #pobjs where ord_id=ordid order by nid ' 
execute(@sql) 
exec drop_temp_table '#pobjs' 
return 
end 

-- 返回有多少条记录
set @sql = 'select count(1) cnt  from  '+@sdbname+@stbname+'_relation sr, '+
@rdbname+@rtbname+'_users su where su.ordp_ordid=sr.ordr_rordid and su.ordp_type=''bizview'' and su.ordp_cuid=@useruid and '+
' sr.ordr_ordid=@ordid and sr.ordr_rcrmid=@rcrmid  '  
EXECUTE sp_executesql @sql,N'@rcrmid int,@ordid bigint,@useruid int',@rcrmid,@ordid,@useruid 

-- 返回所有的记录
set @sql = 'select top '+ltrim(rtrim(str(@amount)))+' sr.ordr_rordid  from  '+@sdbname+@stbname+'_relation sr, '+
@rdbname+@rtbname+'_users su where su.ordp_ordid=sr.ordr_rordid and su.ordp_type=''bizview'' and su.ordp_cuid=@useruid and '+
' sr.ordr_ordid=@ordid and sr.ordr_rcrmid=@rcrmid order by  sr.ordr_rordid desc '  
EXECUTE sp_executesql @sql,N'@rcrmid int,@ordid bigint,@useruid int',@rcrmid,@ordid,@useruid 

-- 返回第一页 
set @sql = 'select top '+ltrim(rtrim(str(@pagesize)))+' r.*  from  '+@rdbname+@rtbname+' r ,'+@sdbname+@stbname+'_relation sr, '+
@rdbname+@rtbname+'_users su where su.ordp_ordid=sr.ordr_rordid and su.ordp_type=''bizview'' and su.ordp_cuid=@useruid and '+
' sr.ordr_ordid=@ordid and sr.ordr_rcrmid=@rcrmid and r.ord_id=sr.ordr_rordid order by  sr.ordr_rordid desc '  
EXECUTE sp_executesql @sql,N'@rcrmid int,@ordid bigint,@useruid int',@rcrmid,@ordid,@useruid 

exec drop_temp_table '#pobjs' 
set nocount off
end