-- Copyright (c) 2015 gutlib.com - All rights reserved. Terms are in gutlib.sql
-- You are NOT ALLOWED to modify and/or use this code without author permission

exec g.sp 'g.do'
go
alter procedure g.do
    @arg nvarchar(128) -- name of temp table passed as parameter
   ,@cmd nvarchar(max)
as
   if @arg is not null and @arg like '#%' begin
      declare
          @replace nvarchar(max) = ''
         ,@with nvarchar(max) = ''
      select
          @replace += 'replace('
         ,@with +='
            ,''|' + col.name + '|''
               ,' + col.name + ')'
         from tempdb.sys.columns col
         where object_id = object_id('tempdb..' + @arg)

      declare @exec nvarchar(max) = '
         select @cmd = ' + @replace + ' @cmd
         ' + @with + '
         from ' + @arg + '
      '
      select @cmd = g.nest_str(@cmd)
      exec sp_executesql @exec,N'@cmd nvarchar(max) out' ,@cmd out

      if g.debugging() = 1
         exec g.log @cmd
      exec sp_executesql @cmd
   end

go -- unit tests
if object_id('tempdb..#arg') is not null
   drop table #arg
select tbl = 'sys.objects' into #arg
exec g.do "#arg","
   declare @c varchar = (select convert(varchar,count(1)) from |tbl|)
   print {|tbl| } + @c
"
