SET @COLUMN_NAME = 'ColumnNameYouWantToAdd';SET @COLUMN_DATATYPE = 'DataTypeOfColumn';------------------------------------------------Code---------------------------------------------------USE TESTDB;GO--Declare VariablesDECLARE @TableName VARCHAR(100);DECLARE @TableSchema VARCHAR(100);DECLARE @COLUMN_NAME VARCHAR(50);SET @COLUMN_NAME = 'CreatedOn'; -- Change Column Name according to your requirementDECLARE @COLUMN_DATATYPE VARCHAR(50);SET @COLUMN_DATATYPE = 'DateTime'; -- Provide data type for column--Declare CursorDECLARE CUR CURSOR FORSELECT TABLE_SCHEMA, TABLE_NAMEFROM INFORMATION_SCHEMA.TABLESWHERE TABLE_TYPE = 'BASE TABLE';--OPEN CURSOROPEN CUR;--Fetch First RowFETCH NEXT FROM CURINTO @TableSchema, @TableName;--LoopWHILE @@FETCH_STATUS = 0BEGIN DECLARE @SQL NVARCHAR(MAX); SET @SQL = NULL; IF NOT EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @COLUMN_NAME AND TABLE_SCHEMA = @TableSchema ) BEGIN SET @SQL = 'ALTER TABLE ' + @TableSchema + '.' + @TableName + ' ADD ' + @COLUMN_NAME + ' ' + @COLUMN_DATATYPE + ' '; PRINT @SQL; EXEC (@SQL); END; IF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @COLUMN_NAME AND TABLE_SCHEMA = @TableSchema ) BEGIN PRINT 'Column Already exists in Table'; END; FETCH NEXT FROM CUR INTO @TableSchema, @TableName;END;--Close and Deallocate CursorCLOSE CUR;DEALLOCATE CUR;
posted on 2018-01-29 16:12 阅读( ...) 评论( ...)