IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_warehouse]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_warehouse]
GO

CREATE  procedure [dbo].[mps_g_warehouse](
@cmpid int,
@branchid int,
@pagesize int , 
@pagecount int , 
@pageobjids varchar(8000),
@key nvarchar(50)
) 
as 
begin 
 
set nocount on  

declare @nonedate datetime 
set @nonedate = CONVERT(datetime,'1910-1-1') 
declare @s1 varchar(8000) 
declare @s2 varchar(100) 
declare @i int 
declare @amount int 
select @amount = @pagecount*@pagesize 
declare @pobjs table(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 
select a.* from mps_warehouse a, @pobjs
where wh_id=ordid
order by nid 
return 
end 

set @key = '%'+@key+'%' 
select count(1) cnt from mps_warehouse  
where wh_cmpid=@cmpid and 
(
 (wh_code like @key ) or 
 (wh_caption like @key) or 
 (wh_location like @key)
) and (@branchid=0 or wh_bcid=@branchid) 

-- 返回所有ID
insert into @pobjs(ordid) select top(@amount) wh_id from mps_warehouse 
where wh_cmpid=@cmpid and 
(
 (wh_code like @key ) or 
 (wh_caption like @key) or 
 (wh_location like @key)
) and (@branchid=0 or wh_bcid=@branchid) 
order by wh_bcid , wh_dpid , wh_code 

select ordid from @pobjs 
order by nid 
-- 返回第一页 
select top(@pagesize) a.* , ISNULL(bc_company,'') bc_company , ISNULL(dp_depart,'') dp_depart  
from mps_warehouse a LEFT OUTER JOIN mps_depart On wh_dpid = dp_id and dp_cmpid=@cmpid 
LEFT OUTER JOIN mps_groupbranch ON wh_bcid = bc_id and bc_cmpid=@cmpid  ,@pobjs 
where a.wh_id=ordid 
order by nid



set nocount off 

end