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

declare status1 cursor LOCAL FORWARD_ONLY READ_ONLY for
  select sql_server,sql_name, sql_type, sql_text, sql_sourcetables, sql_targettables,sql_params,sql_keyparam 
  from pub_sql   
  declare @sql_server varchar(100),@sql_name varchar(100), @sql_type nvarchar(100), @sql_text nvarchar(4000), 
  @sql_sourcetables varchar(200), @sql_targettables varchar(200),@sql_params varchar(2000),@sql_keyparam varchar(30) 
  open status1
  declare @s nvarchar(MAX) 
  set @s='' 
  FETCH NEXT FROM status1 INTO @sql_server,@sql_name, @sql_type, @sql_text, @sql_sourcetables, @sql_targettables,@sql_params,@sql_keyparam
  WHILE (@@FETCH_STATUS = 0)
  BEGIN
set @s = @s+N'
if (not exists(select * from pub_sql where sql_server='''+@sql_server+''' and sql_name='''+@sql_name+N'''))  
begin
insert into pub_sql(sql_server,sql_name, sql_type, sql_text, sql_sourcetables, sql_targettables,sql_params,sql_keyparam) 
values('''+@sql_server+''','''+@sql_name+''','''+@sql_type+''',N'''+replace(@sql_text,'''','''''')+''','+
''''+@sql_sourcetables+''','''+@sql_targettables+''','''+@sql_params+''','''+@sql_keyparam+N'''
)
end else '
print @s
set @s=@s+N'
begin
update pub_sql set 
sql_text=N'''+replace(@sql_text,'''','''''')+N''',
sql_sourcetables='''+@sql_sourcetables+N''',
sql_targettables='''+@sql_targettables+N''',
sql_params='''+@sql_params+N''',
sql_keyparam='''+@sql_keyparam+N'''  
where sql_server='''+@sql_server+''' and sql_name='''+@sql_name+N''' 
end
' 
 
   FETCH NEXT FROM status1 INTO @sql_server,@sql_name, @sql_type, @sql_text, @sql_sourcetables, @sql_targettables,@sql_params,@sql_keyparam
  END
  CLOSE status1
DEALLOCATE status1 


select @s pubsql

end