IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[sys_Sql_loadreplace]') AND type = 'P')
DROP PROCEDURE [dbo].[sys_Sql_loadreplace]
GO
--替换变量取值 ：应该在 
-- exec sys_Sql_loadreplace @cmpid,@parseid,@preblank,@script output

create procedure [dbo].[sys_Sql_loadreplace](
@cmpid int,
@parseid int,
@preblank varchar(50), 
@script varchar(2000) output
)as
begin
declare @repname varchar(50),@repExp varchar(200) ,@dsname varchar(20),@fldname varchar(20)
,@curInd int,@varType varchar(20),@varName varchar(20),@fromInd int,@toInd int,@tmpS varchar(2000)
,@s varchar(500),@tbname varchar(20),@script2 varchar(2000),@lastToInd int,@isNew int

select @script=''
Declare gv cursor static For
select repname,repExp,dsname,fldname 
from sys_sql_replace
where parseid=@parseid

open gv
fetch next from gv into @repname,@repExp,@dsname,@fldname
while (@@fetch_status=0)
begin
select @curInd=1,@fromInd=1

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

set @lastToInd = @toInd
 --首先copy没有匹配的前部
 select @tmpS = substring(@repExp, @curInd,@fromInd - @curInd )
 if (@tmpS is not null)
 select @script=@script + @tmpS

-- 处理global变量
if (@varType='global')
begin
select @s='@'+@repname 
exec sys_sql_addvar @s,'varchar',500,0,@isNew output  --global变量定义

select @script = @script + @preblank + 'select ' + @s + '=g_value from mps_global ' + 
'  where g_cmpid=' + convert(varchar(10),@cmpid) + 
' and (g_name=''' + @varName +''' or g_caption=''' + @varname + ''')' + char(13)

end
if (@varType='field')
begin
 select @tbname=tbname from flatFld where parseId=@parseid and fldname=ltrim(rtrim(@varname))
 exec sys_sql_loadtable  @cmpid,@parseid,@tbname,@preblank,@script2 output
 
 if (@script2 is not null)
 select @script = @script + @script2
end


nxt:
fetch next from gv into @repname,@repExp,@dsname,@fldname
end
close gv
deallocate gv

end