IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_1doc_full]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_1doc_full]
GO
CREATE  procedure [dbo].[mps_g_1doc_full](
@cmpid int,
@useruid int ,  
@usersecurity int,
    @docid bigint, 
    @dcid int) 
as  
begin  
set nocount on 
-- 首先取模板  t1 

select top 1 * from mps_template where tmp_cmpid = @cmpid and tmp_type = 'docdisp' and tmp_objid = @dcid 

-- 取正文 t2 
select * from mps_document where doc_id=@docid and doc_cmpid=@cmpid 
select * from mps_document_text where docd_docid=@docid 
    --返回所有附件  t4
    select *, da_categoryid as datagroup from mps_attach 
    where da_cmpid = @cmpid and da_type = 'doc'   and da_objid = @docid and da_objid2 = 0 
    order by da_categoryid 
    
    --返回最新三条评论
    declare @forumnum int
    select @forumnum = COUNT(fm_id) from  mps_forum a
    where a.fm_cmpid = @cmpid  and a.fm_type = 'doc' 
and a.fm_ctgid = convert(varchar(50),@dcid) and a.fm_objid=@docid 

set @forumnum = ISNULL(@forumnum,0)

    declare @forumpobjs table(nid int identity(1, 1), fmid bigint) 
insert into @forumpobjs(fmid)
select top 5 fm_id from mps_forum a
where a.fm_cmpid = @cmpid and a.fm_ffmid=0 and a.fm_type = 'doc' 
and a.fm_ctgid = convert(varchar(50),@dcid) and a.fm_objid=@docid 
order by a.fm_id desc

--查询出回复
declare @strforum varchar(max) = ''
select @strforum = stuff((
select ' fm_id = '+convert(varchar(100),fmid)+ ' or '
from @forumpobjs for xml path('')),1,1,'')
set @strforum = isnull(@strforum,'')

--查询出主回复的回复
declare @strforum1 varchar(max) = ''
select @strforum1 = stuff((
select ' fm_ffmid = '+convert(varchar(100),fmid)+' or fm_fffmid = ' +convert(varchar(100),fmid)+ ' or '
from @forumpobjs for xml path('')),1,1,'')

set @strforum1 = isnull(@strforum1,'')

if @strforum1 > ''
begin
set @strforum1 = @strforum +substring(@strforum1,1,len(@strforum1)-3)
set @strforum1 = ' select 1 as fm_bizforum,*,'+convert(varchar(50),@forumnum)+' as fm_forumnum from mps_forum a where ' + @strforum1
 + ' order by fm_id desc'
exec(@strforum1)
end
    
set nocount off
end