IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_query_mobile_orderselect]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_query_mobile_orderselect]
GO
create proc [dbo].[mps_query_mobile_orderselect]
@cmpid int,
@branchid int,
@bizid int , 
@useruid int ,
@useradmin int,
@userdpstid int,
@userdpid int,
@userotid int,
@mobile int --0=mobile 1=pc 
AS
BEGIN
set nocount on
create table #pobj(ctgid int) 
insert into #pobj exec [mps_biztype_query_authority] @cmpid,@branchid,@bizid,@useradmin,@userdpstid,@userdpid,@userotid
declare @t table(bql_id int)
-- 先搜索与个人有关的
insert into @t(bql_id)
select bql_id 
from mps_biztype_query with(nolock) , mps_biztype_query_users,#pobj with(nolock) 
where bqlu_bqlid=bql_id and bqlu_cuid=@useruid and bql_cmpid=@cmpid 
and bql_bizid=@bizid and ctgid=bql_id and bql_status=0
order by bql_order 

-- 再搜索缺省的
if (((@mobile=1) and (not exists (select 1 from @t))) or (@mobile=0))
begin
insert into @t(bql_id)
select bql_id 
from mps_biztype_query a with(nolock),#pobj  
where bql_cmpid=@cmpid and bql_status=0 and bql_bizid=@bizid and ctgid=bql_id  and 
(not exists (select 1 from @t b where a.bql_id=b.bql_id)) 
order by bql_order 
end 


-- 再搜索所有的
if (@mobile=0) 
begin
insert into @t(bql_id)
select bql_id 
from mps_biztype_query a with(nolock),#pobj  
where bql_cmpid=@cmpid and bql_status=1  and bql_bizid=@bizid and ctgid=bql_id and 
(not exists (select 1 from @t b where a.bql_id=b.bql_id)) 
order by bql_order 
end else
begin
if (not exists (select 1 from @t)) 
begin
insert into @t(bql_id)
select top 5 bql_id 
from mps_biztype_query a with(nolock) ,#pobj 
where bql_cmpid=@cmpid and bql_status=1  and bql_bizid=@bizid and ctgid=bql_id and 
(not exists (select 1 from @t b where a.bql_id=b.bql_id)) 
order by bql_order 
end 
end 

select a.* from @t b , mps_biztype_query a with(nolock)  
where a.bql_id=b.bql_id and bql_sql>'' 
order by a.bql_order 

select bqlu_bqlid from mps_biztype_query_users with(nolock) where bqlu_bizid=@bizid and bqlu_cuid=@useruid

drop table #pobj
set nocount off 
END