IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_query_orderselet]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_query_orderselet]
GO
create proc [dbo].[mps_query_orderselet]
@cmpid int,
@bizid int,
@useruid int,
@dpid int,
@otid int
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--整理字段临时表
create table #temp(
bqgroup nvarchar(1000),
content nvarchar(max)
)
--将分组插入临时表
insert into #temp(bqgroup) select distinct(bql_group) from mps_biztype_query bq,mps_biztype_query_users bqu with(nolock) where bq.bql_id=bqu.bqlu_bqlid 
and bqu.bqlu_cuid=@useruid and bqu.bqlu_bizid=@bizid and  bq.bql_group <> ''
--将分组下的条件更新至对应临时表
update #temp set #temp.content=stuff((select '|'+bql_caption+'=clickmenuitem(this,'''+bql_caption+''','+cast(bql_id as nvarchar)+')' from mps_biztype_query bq,mps_biztype_query_users bqu with(nolock) 
where bq.bql_id=bqu.bqlu_bqlid and bqu.bqlu_cuid=@useruid and bqu.bqlu_bizid=@bizid and  bq.bql_group <> '' and #temp.bqgroup=bq.bql_group  for xml path('')),1,1,'')
--返回所有分组
select * from #temp
--查询所有未分组的标签
select * from mps_biztype_query bq,mps_biztype_query_users bqu with(nolock) where bq.bql_id=bqu.bqlu_bqlid 
and bqu.bqlu_cuid=@useruid and bqu.bqlu_bizid=@bizid and bq.bql_group='' order by bql_orderby asc
--返回所有选中的id
select stuff((select ','+cast(bqlu_bqlid as nvarchar) from mps_biztype_query_users bqu where bqu.bqlu_bizid=@bizid and bqu.bqlu_cuid=@useruid for xml path('')),1,1,'') bql_id
--返回全部数据的id
select top 1 bql_id from mps_biztype_query where bql_bizid=@bizid and bql_caption='全部数据'  
--删除临时表
drop table #temp

--生成mps_sql
declare @psql nvarchar(max)
declare @sqlpart nvarchar(max)  
set @sqlpart =  CHAR(10) +CHAR(9)+ '@cmpid int,'+CHAR(13) +CHAR(9)+ 
             '@bizid int,'+CHAR(13) + CHAR(9)+ 
             '@useruid int ,'+CHAR(13) +CHAR(9)+
 '@dpid int ,'+CHAR(13) +CHAR(9)+
 '@otid int ,'+CHAR(13) +CHAR(9)
set @psql = 'exec mps_sys_gen_mpssql '+CONVERT(varchar(10),1)+',mps_query_orderselet,
'+'''' +@sqlpart+''''
execute(@psql)

END