把指定表中的列添加到目标表中不包含的列
CREATE PROC pro_addColumn ( @oldDB VARCHAR(20), @newDB VARCHAR(20), @oldtable VARCHAR(50), @newtable VARCHAR(50) ) AS EXEC ('USE '+ @newDB+'') IF object_id(''+@newtable+'') is null BEGIN PRINT @newtable+'不存在,创建表' EXEC('SELECT * INTO '+@newtable+' FROM '+@oldtable+' WHERE 1=2') PRINT '创建成功' END ELSE BEGIN DECLARE @colname VARCHAR(30) DECLARE @datatype VARCHAR(20) DECLARE @length VARCHAR(20) EXEC ('USE '+ @oldDB+'') DECLARE test_cursor CURSOR SCROLL FOR select name ,type_name(xtype) AS datetype,length from syscolumns where id=object_id(''+@oldtable+'') OPEN test_cursor FETCH NEXT FROM test_cursor INTO @colname,@datatype,@length PRINT 'old:'+@colname+' '+@datatype+' '+@length WHILE @@FETCH_STATUS=0 BEGIN EXEC ('USE '+ @newDB+'') IF NOT EXISTS(select name from syscolumns where id=object_id(''+@newtable+'')AND name=@colname) BEGIN PRINT '新表不存在列:'+@colname IF @datatype='int' OR @datatype='bit' OR @datatype='text' OR @datatype='xml' BEGIN PRINT '为表'+@newtable+'添加列:'+@colname+' '+@datatype+' '+@length EXEC(' ALTER TABLE '+@newtable+' ADD '+@colname+' '+@datatype+'') END ELSE IF @length='-1' BEGIN SET @length='MAX' END PRINT '为表'+@newtable+'添加列:'+@colname+' '+@datatype+' '+@length EXEC(' ALTER TABLE '+@newtable+' ADD '+@colname+' '+@datatype+' ('+@length+')') END ELSE BEGIN PRINT '新表中存在列:'+@colname END FETCH NEXT FROM test_cursor INTO @colname,@datatype,@length END CLOSE test_cursor DEALLOCATE test_cursor END