IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_flowscope]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_flowscope]
GO
CREATE procedure [dbo].[mps_save_flowscope] 
@cmpid int , 
@flwid int,
@scope nvarchar(4000)
as
begin
 
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
set @scope = ISNULL(@scope,'') 
if (@scope='_none_') set @scope=''
if (@scope>'') 
begin
update mps_bizflow set flw_scope=@scope where flw_id=@flwid 
end 

declare @bizid int 
select @bizid=flw_bizid from mps_bizflow where flw_id=@flwid 

declare @tbname varchar(50)
declare @dbname varchar(50)
declare @fkey   varchar(50) 
exec sys_sql_getTableNamePk @cmpid,'biz',@bizid,0,@tbname output,@fkey output ,@dbname output 
 
declare c1 cursor LOCAL FORWARD_ONLY READ_ONLY for
select flw_id,flw_scope  from mps_bizflow  where flw_bizid= @bizid and  len(flw_scope)>5 and flw_title<>'缺省流程' 


declare @tmp_id int 
declare @tmp_scope nvarchar(4000)  
declare @sql nvarchar(4000) 
set @sql = '' 

open c1
set @sql = '' 
FETCH NEXT FROM c1 INTO @tmp_id,@tmp_scope 
WHILE (@@FETCH_STATUS = 0)
BEGIN
if (@sql>'') set @sql = @sql +';' 
 set @sql = @sql+N'if (not exists (select 1 from @t)) '+char(13)+CHAR(10)+
 'insert into @t(tmpid) '+char(13)+CHAR(10)+
 'select '+convert(varchar(10),@tmp_id)+CHAR(13)+CHAR(10)+
 'from '+@dbname+@tbname+' with(nolock), mps_flowwork with(nolock) '+CHAR(13)+CHAR(10)+
 'where wrk_id=@wrkid and ord_id=@ordid and ('+@tmp_scope+')'+CHAR(13)+CHAR(10) 
 FETCH NEXT FROM c1 INTO @tmp_id,@tmp_scope 
END
CLOSE c1
DEALLOCATE c1 

if (len(@sql)>10) 
begin
if (dbo.checkprocedure(@tbname+'_set_subflow')=0) 
set @sql = 'alter procedure '+@tbname+N'_set_subflow('+CHAR(13)+
'@cmpid int,'+CHAR(13)+
'@branchid int,'+CHAR(13)+
'@userpdid int,'+CHAR(13)+
'@useruid int,'+CHAR(13)+
'@userotid int,'+CHAR(13)+
'@useradmin int,'+CHAR(13)+
'@usertype int,'+CHAR(13)+
'@userctid int,'+CHAR(13)+
'@ordid bigint,'+CHAR(13)+
'@wrkid int,'+CHAR(13)+
'@wsid int,'+CHAR(13)+
'@flwid int output)'+CHAR(13)+
'as'+CHAR(13)+
'begin'+CHAR(13)+
'declare @t table(tmpid int) '+CHAR(13)+@sql 
else 
set @sql = 'create procedure '+@tbname+N'_set_subflow('+CHAR(13)+
'@cmpid int,'+CHAR(13)+
'@branchid int,'+CHAR(13)+
'@userpdid int,'+CHAR(13)+
'@useruid int,'+CHAR(13)+
'@userotid int,'+CHAR(13)+
'@useradmin int,'+CHAR(13)+
'@usertype int,'+CHAR(13)+
'@userctid int,'+CHAR(13)+
'@ordid bigint,'+CHAR(13)+
'@wrkid int,'+CHAR(13)+
'@wsid int,'+CHAR(13)+
'@flwid int output)'+
'as'+CHAR(13)+
'begin'+CHAR(13)+
'declare @t table(tmpid int) '+CHAR(13)+@sql 
set @sql = @sql+CHAR(13)+
'set @flwid=0'+CHAR(13)+
'select top 1 @flwid=tmpid from @t  ' +CHAR(13)+
' end ' 
execute(@sql)
endelse 
begin
if (dbo.checkprocedure(@tbname+'_set_subflow')=0)
begin
set @sql = 'drop procedure '+@tbname+'_set_subflow' 
execute(@sql)
end
end
print @sql
end