IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[sys_sql_command_cursor]') AND type = 'P')
DROP PROCEDURE [dbo].[sys_sql_command_cursor]
GO

create procedure [dbo].[sys_sql_command_cursor] (
@cmpid int,
@parseid int ,
@preblank varchar(50),
@script varchar(max) output
)As
begin
--从级别信息中取游标信息
set @script = ''
declare @ttable varchar(50),@parsedscript varchar(1000)
select @ttable=ttable,@parsedscript=parsedscript
  from sys_sql_inf 
  where parseid=@parseid
  
declare @startInd int,@varType varchar(10),@varName varchar(20),@frmInd int,@toInd int,@targDs varchar(50),
@cstbname varchar(50),@predsname varchar(50),@script2 varchar(max),@pretbname varchar(20),
@glparseid int,@tbdatabase varchar(30)
--目标数据源
select @startInd=1,@varType='',@varName=''
exec sys_sql_getNextSysVar @ttable,@startInd ,@varType output,@varName output,@frmInd output,@toInd output
if (@varType !='ds')
return
select @glparseid=glparseid
from sys_Sql_inf where parseid=@parseid

select @targDS=@varName
select @cstbname=tbname,@predsname=predsname,@tbdatabase=tbdatabase
from flatDSS
where parseid=@parseid and dsname=@targDS

if (@tbdatabase is null)
set @tbdatabase=''

select @pretbname=pretbname from flatDSS where parseid=@glparseid and tbname=@cstbname

--生成游标字段
declare @flds varchar(2000), @fldvars varchar(2000),@fldvals varchar(2000),@csname varchar(50)
--生成游标字段 
exec sys_sql_get_flds @parseid,@cstbname,0,@flds output,@fldvars output,@fldvals output
 -- 可以完善游标名称命名机制
select @csname='newBIz_cs_'+@cstbname
insert into flatCursor(cursorname) values(@csname)

--游标头
select @script=@preblank +'  -- 明细表，定义游标 : ' + @cstbname + char(13)+
@preblank +' -- ' + char(13) +
@preblank +'DECLARE ' + @csname +' Cursor static For ' + char(13) +
@preblank +'    select ' + @flds + char(13) +
@preblank +'        from ' + @tbdatabase + @cstbname + char(13) + 
@preblank +'        where ord2_ordid=@' + @pretbname + '_ord_id__'  +char(13) +
@preblank +'   --游标操作 ' + char(13) +
@preblank +'OPEN '+@csname  + char(13) +
@preblank +'FETCH NEXT FROM  ' + @csname +' INTO  '+ @fldvars + char(13) +
@preblank +'WHILE (@@FETCH_STATUS=0) ' + char(13) +
@preblank +'BEGIN ' + char(13) 
  update flatDSS
  set isLoaded = 1
  where tbname=@cstbname
  --游标体
  declare @preb varchar(50)
  select  @preb = @preblank + '  '
  --sys_sql_deal_block@cmpid,@parseid,@srcText,@preblank,@inCursorDS,@curtbname,@script output
exec sys_sql_deal_block @cmpid,@parseid,@parsedscript,@preb,@targDS,@cstbname,@script2 output
if (@script2 is not null)
select @script=@script + @script2

--游标尾
select @script=@script +
@preblank +'  FETCH NEXT FROM  ' + @csname +' INTO  '+ @fldvars + char(13) +
  @preblank +'END ' + char(13) +
@preblank +'CLOSE  ' +@csname  + char(13) +
@preblank +'DEALLOCATE  ' +@csname  + char(13) 

delete flatCursor where cursorname =@csname

--从parsedscriptz中提取
end