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

create procedure [dbo].[sys_sql_genlogtable](
@tablename nvarchar(30)
)
as
begin
Declare @sql nvarchar(2000),@indexJob varchar(50),@indexObj varchar(50)
if object_id(@tablename,N'U') is null
begin
select @indexJob='sys_index_'+@tablename+'_job'
select @indexObj='sys_index_'+@tablename+'_obj'
select @sql =

'create table ' + @tablename + ' ( '+ char(13) +
'   logrecid             int                  identity, ' + char(13) +
'   jobid                int                  null,' + char(13) +
'   objectid             int                  null,' + char(13) +
'   fldid                int                  null,' + char(13) +
'   oldval               varchar(200)         null,' + char(13) +
'   newval               varchar(200)         null,' + char(13) +
'   isreversed           tinyint              null,' + char(13) + 
'   optype           tinyint              null,' + char(13) + 
'   constraint PK_LOG_' + @tablename+ ' primary key (logrecid)' + char(13) +
')' + char(13) 

exec sp_executesql @sql
select @sql =
'create index '+ @indexJob + '  on ' + @tablename + ' ( ' +char(13) +
'objectid ASC ' +char(13) +
') ' 
exec sp_executesql @sql
select @sql =

'create index '+@indexObj + '  on ' + @tablename + ' ( ' +char(13) +
'jobid ASC ' +char(13) +
') ' +char(13) 


exec sp_executesql @sql
end

end