CREATE PROCEDURE spAutoProc_ZField @SourceTableName varchar(50), @TargetTableName varchar(50), @FieldMapTable varchar(50)
AS
DECLARE @altQuery nvarchar(1000),
@sql nvarchar(1000),
@updQuery nvarchar(1000),
@colName nvarchar(100),
@idx1 int,
@idx2 int
SELECT @sql =
' DECLARE cs_AltQuery CURSOR FOR ' +
' SELECT ' +
'''ALTER TABLE ''+''' + @SourceTableName + '''+'' ADD z''+' + 'COLUMN_NAME' + '+'' ''' +
' +DATA_TYPE+ ' + 'CASE ' +
' WHEN character_maximum_length IS NULL AND numeric_scale IS NULL THEN ''(''+ cast(NUMERIC_PRECISION AS varchar(10)) + '')''' +
' WHEN character_maximum_length IS NULL AND NOT numeric_scale = 0 THEN ''(''+ cast(NUMERIC_PRECISION AS varchar(10))+' + ''', ''' + '+cast(NUMERIC_SCALE AS varchar(10)) + '')''' +
' WHEN character_maximum_length IS NULL AND numeric_scale = 0 THEN '' ''' +
' ELSE ''(''+ cast(character_maximum_length AS varchar(10)) + '')'' END +' +
' '' NULL''' +
' FROM information_schema.columns ' +
' WHERE TABLE_NAME = ''' + @TargetTableName + ''' AND ' +
' COLUMN_NAME IN (SELECT ColumnName FROM ' + @FieldMapTable +
' WHERE SourceTableName = ''' + @SourceTableName + ''' AND ' +
' Flag = 0 )'
EXEC sp_executesql @sql
OPEN cs_AltQuery
FETCH NEXT FROM cs_AltQuery INTO @altQuery
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Processing query ''' + @altQuery + ''' ...'
SELECT @idx1 = CHARINDEX(' ', @altQuery, 16+LEN(@SourceTableName))
SELECT @idx2 = CHARINDEX(' ', @altQuery, 1+@idx1)
SELECT @colName = SUBSTRING(@altQuery, 2+@idx1, @idx2-@idx1-1)
EXEC (@altQuery)
SELECT @updQuery = ' UPDATE ' + @FieldMapTable +
' SET Flag = 1 ' +
' WHERE ColumnName = ''' + @colName + ''''
EXEC (@updQuery)
PRINT 'The query ''' + @altQuery + ''' has been successfully processed.'
FETCH NEXT FROM cs_AltQuery INTO @altQuery
END
CLOSE cs_AltQuery
DEALLOCATE cs_AltQuery