IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_sys_gen_userfunc]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_sys_gen_userfunc]
GO
CREATE PROCEDURE [dbo].[mps_sys_gen_userfunc]
@cmpid int,
@tmpid int,
@parsesql text
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
declare @s1  varchar(max)
declare @s  varchar(max)
declare @procname  varchar(100)
declare @procparams  varchar(1000)
declare @sql  nvarchar(max)
set @s=@parsesql
set @sql=''

declare @objtype varchar(20) 
declare @objctgid int 
select top 1 @objctgid=tmp_objid , @objtype=tmp_type from mps_template where tmp_id=@tmpid 

--从mps_sql中获取存储过程的名称
select @sql+='DROP PROCEDURE ' + sql_name+';delete from mps_sql where sql_name = '''+sql_name+''';'
from mps_sql
where sql_name like 'userfunc_'+CONVERT(varchar,@tmpid)+'%'
exec sp_executesql @sql


declare @index int
while (@s>'') 
begin
set @index=CHARINDEX('_____PROCEDURE_____',@s)
if (@index>0)
begin
set @s1 = substring(@s,1,@index-1) 
set @s  = substring(@s,@index+19,len(@s))
end else 
begin
set @s1 = @s 
set @s = '' 
end 
if (@s1>'')
begin
--开始拼凑SQL
--填充tmpid
set @s1=REPLACE(@s1,'_{tmpid}_','_'+CONVERT(varchar,@tmpid)+'_');
--获取变量列表
set @index = CHARINDEX('_____PARAMS_____',@s1);
set @procparams=SUBSTRING(@s1,1,@index-1)
set @s1=SUBSTRING(@s1,@index+16,LEN(@s1))
--获取存储过程名称
set @procname=SUBSTRING(@s1,1,CHARINDEX('(',@s1)-1)
--if OBJECT_ID(@procname) is null
--begin
set @sql='CREATE PROCEDURE '
--end else begin
--set @sql='ALTER PROCEDURE '
--end
set @sql += @s1
select @procparams as params
select @procname params

if (@objtype='biz' or @objtype='bizprint') 
begin
exec mps_genformextsql_biz @cmpid,@objctgid,@sql output 
end 
set @sql = REPLACE(@sql,'{{firstautosql}}','') 
set @sql = REPLACE(@sql,'{{lastautosql}}','') 
exec sp_executesql @sql
exec mps_sys_gen_mpssql @cmpid,@procname,@procparams
end
end


END