IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[sys_qry_decomlabels]') AND type = 'P')
DROP PROCEDURE [dbo].[sys_qry_decomlabels]
GO
-- 
create procedure [dbo].[sys_qry_decomlabels] (
@labelstr varchar(2000),
@ljionname varchar(20),      --左连接表名称
@ljoinfld  varchar(20), --左连接字段名称
@tablePrefix   varchar(30),
@jionclause varchar(2000) output
) as
begin
set @jionclause=''
if (@labelstr is null)
set @labelstr=''
if (@ljionname is null)
set @ljionname=''
if (@ljoinfld is null)
set @ljoinfld=''
if (@tablePrefix is null)
set @tablePrefix='';
if (@labelstr='' or @ljionname = '' or @ljoinfld='' or @tablePrefix='')
  return
  
declare @s1 varchar(20),@totl int,@curInd int,
@curChar varchar(2),@preChar varchar(2),@curWord varchar(20),
@curLabel varchar(20),@frmVal varchar(20),@toVal varchar(20),
@labeltable varchar(40),@curstate int,@cnt int,@aliasName varchar(10)

set @totl = len(@labelstr)
--当前字符串位置，当前字符，前字符，当前单词,当前标签名称，标签起始值，标签结束值
select @curInd=1,@curChar = '',@preChar='',@curWord='',@curLabel='',@frmVal='',@toVal='',@cnt=1

--@curstate : 状态  0=表识别状态  1：起始值识别状态  2：结束值识别状态 
set @curstate= 0

while @curInd<=@totl + 1
begin
set @preChar = @curChar;
--取当前字符
if (@curInd<=@totl)
select  @curChar=SUBSTRING(@labelstr,@curInd,1)

if (@curChar=':')
begin
    select @labeltable = @tablePrefix + '_' + @curLabel, --标签表
    @curstate=1 --状态转换
end
else if (@curChar='-')
  select @curstate=2
else if (@curChar=',' or (@curInd>@totl))  --识别完一个标签
begin
  select @aliasName='____'+  ltrim(rtrim(str(@cnt))),@labeltable = @tablePrefix + '_' + @curLabel --标签表
  select @jionclause= @jionclause +' join ' + @labeltable + '  ' + @aliasName + 
      ' on ' + @ljionname + '.' + @ljoinfld + '=' + @aliasName + + '.objectid'
  if (@frmVal <> '')
     select @jionclause= @jionclause + ' and ' + @aliasName + '.objectval>=' + @frmVal
  if (@toVal <> '')
     select @jionclause= @jionclause + ' and ' + @aliasName + '.objectval<=' + @toVal
 
  select @curstate=0,@curChar = '',@preChar='',@curWord='',@curLabel='',@frmVal='',@toVal=''
  
  set @cnt=@cnt+1
end
else   -- 非分割符号
begin
if (@curChar =' ')
  select @curChar=''
if (@curstate=0)
  select @curLabel = @curLabel + @curChar
else if(@curstate=1)
select @frmVal=@frmVal + @curChar
else
select @toVal=@toVal + @curChar
end
select @curInd = @curInd+1
end
end