IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[sys_sql_replaceExp]') AND type = 'P')
DROP PROCEDURE [dbo].[sys_sql_replaceExp]
GO
create procedure [dbo].[sys_sql_replaceExp](
@parseid int,
@exp varchar(4000),
@re varchar(4000) out
)
as
begin
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--如果返回varName 为空，则没有变量
set @re = ''
Declare @curInd int,@varType varchar(10),@varName varchar(20),@fromInd int,@toInd int,@expLen int,
@fldvar varchar(50),@lastToInd int,@str varchar(1000),@fldexp varchar(400)
select @curInd = 1,@expLen = len(@exp),@re='',@lastToInd=0,@toInd = 0

-- 下面循环，每次处理一个系统变量
while (@curInd<@expLen)
begin

exec sys_sql_getNextSysVar @exp,@curInd,@varType output,@varName output,@fromInd output ,@toInd output
--结束判断
if (@varType is null or @varName is null) -- 为空，忽略该变量
break

set @lastToInd = @toInd

 --首先copy没有匹配的前部
 select @re=@re + substring(@exp, @curInd,@fromInd - @curInd )
 --替换变量
 if (@varType='web')
 select @re=@re + @varName

 if (@varType='function')
 select @re=@re + @varName
 
 if (@varType='field')
 begin
 select @fldvar=fldvar,@fldexp=fldexp
 from flatFld
 where parseid=@parseid and fldname=@varName -- and fldvar is not null
 
 if (@fldvar is not null)
 select @re=@re + @fldvar
 else if (@fldexp  is not null) 
 select @re=@re + @fldexp
 else
 select @re=@re + @varname
 
 end

 if (@varType='const')
 begin
 select @str=constval
 from sys_sql_const
 where parseid=@parseid and constname=@varName
 if (@str is not null)
 select @re=@re + @str
 end
 
 --下个变量
 nxt:
 select @curInd = @toInd 
end
--最后非变量处理
 if (@lastToInd<@expLen)
 select @re=@re  + substring(@exp, @lastToInd+1,@expLen)

end