IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_account_details]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_account_details]
GO
create proc [dbo].[mps_g_account_details]
@cmpid int,
@aiid bigint,
@pagesize int ,
@pagecount int,
@pageobjids varchar(8000) 
as
begin
set nocount on
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
insert into mps_account_branch select 0,@aiid,0,1,1 where 
not exists(select 1 from mps_account_branch where aib_bcid = 0 and aib_aiid=@aiid); 

insert into mps_account_branch select bc_id,@aiid,0,1,1 from mps_branch b
where not exists(select 1 from mps_account_branch where aib_bcid = b.bc_id and aib_aiid=@aiid);

declare @acbc table(id int identity(1,1) , 
aib_id bigint,
aib_bcid bigint,
aib_aiid bigint,
aib_ownerdpid bigint,
aib_budget bigint,
aib_use int,
bc_company nvarchar(200),
dp_depart nvarchar(200))

insert @acbc select a.* ,
case when a.aib_bcid = 0 then '集团总部' 
else (select b.bc_company from mps_branch b where b.bc_id=a.aib_bcid) end as bc_company,
case when a.aib_ownerdpid = 0 then ''
else (select c.dp_depart  from mps_depart c where a.aib_ownerdpid = c.dp_id) end as dp_depart
from mps_account_branch a
where a.aib_aiid = @aiid
order by aib_use,aib_id

declare @amount int 
set @amount=@pagecount*@pagesize

declare @pobjs table(nid int identity(1,1) , lgid bigint)
declare @s1 varchar(8000)
declare @s2 varchar(100) 
declare @i int
set @s1 = @pageobjids 
if (@s1='_none_') set @s1=''
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 
  if (@s2>'') insert into @pobjs(lgid) values(convert(bigint,@s2)) 
end
if (exists (select * from @pobjs))
begin
select * 
from @acbc ,@pobjs
where id=lgid order by nid 
return ;
end

select count(1) as reccount from @acbc

select top(@amount) id
from @acbc
order by id

select top(@pagesize) *
from @acbc
order by id

set nocount off
 end